C++ 构造函数与this指针
? ? ? ? ?之前一直理解的構造函數的參數里沒有this指針,因為此時對象還沒生成,其他非static成員函數才有this指針,因為當它們被調用時對象已經生成了。然而這樣理解是錯誤的,構造函數參數里也是有this指針的,但這個this指針只是指向了一個內存地址,這個內存地址還并不代表一個類對象,當構造函數完成后,這個地址有足夠的信息后才表示這是一個類對象。
#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 那行添加斷點,如:
?從這里應該可以看出,在構造函數之前,this指針已經分配了,指向的內存為0x602010,那我們可以看下這個內存里有什么,如:
?此時內存里都是0,這里的x/8xw 表示打印8個單元內容,每個單元4個字節,以16進制顯示,因為sizeof(CBase) = 32,所以這里打印了 32 個字節的內容。再單步往下執行,會調用 struct Test結構體的構造函數,及進行到初始化列表,如:
?到這里已經進到構造函數里面了,其成員數據已經初始化完成,我們可以看到此時this指向的內存的內容發生了變化,this指向的前4個字節變成了 0x00000064,其10進制就是:100,就是初始化列表里的?mValue(100),最后兩個應該是std::string 變量里的值(std::string 的內存結構這里不詳述,有興趣的同學可以去研究一下)。然后非static成員函數調用時,此時this指針指向的內容就是構造函數構造出來的內容,如:
所以,我們可以得出,構造函數里的this指針指向的就是一塊空內存(內容可能也是隨機的),而非static成員函數里的this指針,其內存里已經有了初始化值(通過初始化列表或構造函數里賦值)。我們這里是用到了 new 操作符,那我們可以看一下 new 操作符是怎樣工作的,這樣也可以驗證我們的結論。這里找到的文檔為?microsoft 的文檔:new 操作符如何工作,截取一段內容:
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.
文檔里說明,第一步完成時,此時所分配的內存并未表示是一個 “對象”,當第2步完成后,此時的內存才表示是一個“對象”。
總結
以上是生活随笔為你收集整理的C++ 构造函数与this指针的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装kivy
- 下一篇: WorkNC3D沿面精加工技巧分享