C++ 构造函数与this指针
? ? ? ? ?之前一直理解的構(gòu)造函數(shù)的參數(shù)里沒有this指針,因為此時對象還沒生成,其他非static成員函數(shù)才有this指針,因為當它們被調(diào)用時對象已經(jīng)生成了。然而這樣理解是錯誤的,構(gòu)造函數(shù)參數(shù)里也是有this指針的,但這個this指針只是指向了一個內(nèi)存地址,這個內(nèi)存地址還并不代表一個類對象,當構(gòu)造函數(shù)完成后,這個地址有足夠的信息后才表示這是一個類對象。
#include <stdio.h> #include <stdlib.h> #include <string>struct Test {char a;int b;int c;std::string str; };class CBase { public:CBase(): mValue(100){printf("constructor, mValue = %d\n", mValue); }~CBase(){printf("destructor\n"); }int getValue()const{return mValue;} private:int mValue;Test mData; };int main() {printf("sizeof(CBase) = %lu\n", sizeof(CBase));CBase *instance = new CBase();int value = instance->getValue();delete instance;return 0; }在 new 那行添加斷點,如:
?從這里應(yīng)該可以看出,在構(gòu)造函數(shù)之前,this指針已經(jīng)分配了,指向的內(nèi)存為0x602010,那我們可以看下這個內(nèi)存里有什么,如:
?此時內(nèi)存里都是0,這里的x/8xw 表示打印8個單元內(nèi)容,每個單元4個字節(jié),以16進制顯示,因為sizeof(CBase) = 32,所以這里打印了 32 個字節(jié)的內(nèi)容。再單步往下執(zhí)行,會調(diào)用 struct Test結(jié)構(gòu)體的構(gòu)造函數(shù),及進行到初始化列表,如:
?到這里已經(jīng)進到構(gòu)造函數(shù)里面了,其成員數(shù)據(jù)已經(jīng)初始化完成,我們可以看到此時this指向的內(nèi)存的內(nèi)容發(fā)生了變化,this指向的前4個字節(jié)變成了 0x00000064,其10進制就是:100,就是初始化列表里的?mValue(100),最后兩個應(yīng)該是std::string 變量里的值(std::string 的內(nèi)存結(jié)構(gòu)這里不詳述,有興趣的同學可以去研究一下)。然后非static成員函數(shù)調(diào)用時,此時this指針指向的內(nèi)容就是構(gòu)造函數(shù)構(gòu)造出來的內(nèi)容,如:
所以,我們可以得出,構(gòu)造函數(shù)里的this指針指向的就是一塊空內(nèi)存(內(nèi)容可能也是隨機的),而非static成員函數(shù)里的this指針,其內(nèi)存里已經(jīng)有了初始化值(通過初始化列表或構(gòu)造函數(shù)里賦值)。我們這里是用到了 new 操作符,那我們可以看一下 new 操作符是怎樣工作的,這樣也可以驗證我們的結(jié)論。這里找到的文檔為?microsoft 的文檔:new 操作符如何工作,截取一段內(nèi)容:
How?new?works
The?new-expression?(the expression containing the?new?operator) does three things:
-
Locates and reserves storage for the object or objects to be allocated. When this stage is complete, the correct amount of storage is allocated, but it's not yet an object.
-
Initializes the object(s). Once initialization is complete, enough information is present for the allocated storage to be an object.
-
Returns a pointer to the object(s) of a pointer type derived from?new-type-id?or?type-id. The program uses this pointer to access the newly allocated object.
The?new?operator invokes the function?operator new. For arrays of any type, and for objects that aren't?class,?struct, or?union?types, a global function,?::operator new, is called to allocate storage. Class-type objects can define their own?operator new?static member function on a per-class basis.
When the compiler encounters the?new?operator to allocate an object of type?T, it issues a call to?T::operator new( sizeof(T) )?or, if no user-defined?operator new?is defined,?::operator new( sizeof(T) ). It's how the?new?operator can allocate the correct amount of memory for the object.
文檔里說明,第一步完成時,此時所分配的內(nèi)存并未表示是一個 “對象”,當?shù)?步完成后,此時的內(nèi)存才表示是一個“對象”。
總結(jié)
以上是生活随笔為你收集整理的C++ 构造函数与this指针的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装kivy
- 下一篇: C++的this指针【定义、用法、本质、