嵌入式指針 可以union改struct 內存分配后 next指針就沒用了 直接作為數據空間比較省內存 因為對指針指向的內存存儲的時候 編譯器是不管你是什么類型的 ,這里有道練習題可以對指針的概念稍微理解一下:
#include <iostream>
using std::cout;
using std::endl;
class A
{
public:int j = 5;int i = 1;void exec() { i = 2; }
};
class B
{
public:int i = 3;int j = 6;void exec() { i = 4; }
} ;
int main(){A a;B *bp = (B *)&a;B b = *bp;cout<<a.i << bp->i << b.i<<endl;bp->exec();cout<<a.i <<bp->i << b.i<<endl ;b.exec();cout<<a.i << bp->i << b.i<<endl ;
}
由于嵌入式指針節省內存的特點 幾乎所有的內存池都會使用
內存池一般不是為了提高效率而是為了減少cookie,設想一下節省100萬個指針的存儲會節省多少空間。
#include<iostream>
using namespace std;
class TestEP
{
public:int m_i;int m_j;public:struct obj //結構 //定義一個類型,不放在外部,污染全局變量{//成員,是個指針struct obj* next; //這個next就是個嵌入式指針//自己是一個obj結構對象,那么把自己這個對象的next指針指向 另外一個obj結構對象,最終,把多個自己這種類型的對象通過鏈串起來;};
};int main()
{TestEP mytest;cout << sizeof(mytest) << endl; //8TestEP::obj* ptemp; //定義一個指針ptemp = (TestEP::obj*)&mytest; //把對象mytest首地址給了這個指針ptemp,這個指針ptemp指向對象mytest首地址;cout << sizeof(ptemp->next) << endl; //4cout << sizeof(TestEP::obj) << endl; //4ptemp->next = nullptr;return 1;
}