Cpp 对象模型探索 / 编译器为对象创建缺省构造函数的条件
零、前言
? ? ? ?書本上常說,編譯器會給沒有任何構(gòu)造函數(shù)的類自動創(chuàng)建一個缺省的構(gòu)造函數(shù)(沒有形參的構(gòu)造函數(shù))。但是事實上不是這樣么?栗子:
class A { public:int i; };int main() {A a;return 0; }? ? ? ?編譯上述代碼,生成 test1.obj 文件。
? ? ? ?這里為了檢查編譯器是否為我們創(chuàng)建了 a?的構(gòu)造函數(shù),這里我們使用 “ dumpbin /all test1.obj> test1.txt ” 指令。在 vs2019 的Developer PowerShell 中,輸入上述指令,即可在 test1.obj 根目錄下生成了 test1.txt 文件,該文件記錄了一些匯編信息等。
? ? ? ?搜索 “ A::A ” 并沒有在 test1.obj 文件中發(fā)現(xiàn)該信息,說明編譯器并沒有為對象 a 創(chuàng)建缺省的構(gòu)造函數(shù)。
? ? ? ?通過上述驗證,我們發(fā)現(xiàn)編譯器不是在任何情況下都會為沒有建立任何的構(gòu)造函數(shù)的對象創(chuàng)建缺省的構(gòu)造函數(shù)的,只有在必要的情況下才會進行上述操作。
? ? ? ?具體的情況如下:
一、成員中存在含有缺省的構(gòu)造函數(shù)的對象。
栗子:
class B { public:B() {} };class A { public:int i;B b; };int main() {A a;return 0; }結(jié)果:
……COMDAT; sym= "public: __thiscall A::A(void)" (??0A@@QAE@XZ)……二、繼承了帶有缺省的構(gòu)造函數(shù)的類
栗子:?
class B { public:B() {} };class A : public B { public:int i; };int main() {A a;return 0; }結(jié)果:
……COMDAT; sym= "public: __thiscall A::A(void)" (??0A@@QAE@XZ)……三、該類中含有虛函數(shù)。
栗子:
class A { public:int i; public:virtual void func() {}; };int main() {A a;return 0; }結(jié)果:
……COMDAT; sym= "public: __thiscall A::A(void)" (??0A@@QAE@XZ)……四、該類含有虛基類。
栗子:
class Grand {; }; class Father:virtual public Grand {}; class Uncle:virtual public Grand {}; class Son:public Father,public Uncle { public:int i; };int main() {Son sn;return 0; }結(jié)果:
……COMDAT; sym= "public: __thiscall Father::Father(void)" (??0Father@@QAE@XZ)……COMDAT; sym= "public: __thiscall Uncle::Uncle(void)" (??0Uncle@@QAE@XZ)……COMDAT; sym= "public: __thiscall Son::Son(void)" (??0Son@@QAE@XZ)……五、類代碼中存在變量的初始化(C++11)
class A { public:int i = 0; };int main() {A a;return 0; }結(jié)果:
……COMDAT; sym= "public: __thiscall A::A(void)" (??0A@@QAE@XZ)……?
(SAW:Game Over!)
總結(jié)
以上是生活随笔為你收集整理的Cpp 对象模型探索 / 编译器为对象创建缺省构造函数的条件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++对象模型探索 / 子类的内存布局
- 下一篇: 数据结构与算法 / 散列表(HashTa