一个非常奇怪的C++拷贝构造函数问题
生活随笔
收集整理的這篇文章主要介紹了
一个非常奇怪的C++拷贝构造函数问题
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
編譯環(huán)境:VS2022,C++14,對(duì)比測(cè)試如下:
測(cè)試一:
#include <iostream>class CTestA { public:CTestA() {printf("CTestA-contruct\n");}CTestA(const CTestA& other) {printf("copy-construct");}CTestA& operator=(const CTestA& other) = delete; }; int main() {CTestA oa = CTestA();//輸出結(jié)果如下 //CTestA-contruct }通過(guò)該測(cè)試知道:CTestA oa = CTestA()這行代碼導(dǎo)致了構(gòu)造函數(shù)被調(diào)用,但拷貝構(gòu)造函數(shù)并沒(méi)有使用,operator=也沒(méi)有被調(diào)用。
測(cè)試二:
#include <iostream>class CTestA { public:CTestA() {printf("CTestA-contruct\n");}CTestA(const CTestA& other) = delete;CTestA& operator=(const CTestA& other) = delete; }; int main() {CTestA oa = CTestA();}該測(cè)試無(wú)法通過(guò),編譯錯(cuò)誤如下
? ? //1>E:\UETest\TestCPP\TestCPP.cpp(18,1): error C2280: “CTestA::CTestA(const CTestA &)”: 嘗試引用已刪除的函數(shù)。
這說(shuō)明,編譯時(shí)會(huì)嘗試調(diào)用拷貝構(gòu)造函數(shù)!
這就非常奇怪了,通過(guò)測(cè)試一我們知道拷貝構(gòu)造函數(shù)不會(huì)被調(diào)用,而這里又證明它會(huì)被調(diào)用!
沒(méi)搞明白這是怎么回事,猜想可能是編譯時(shí)確實(shí)會(huì)調(diào)用拷貝構(gòu)造函數(shù),但運(yùn)行時(shí)被優(yōu)化掉了?
總結(jié)
以上是生活随笔為你收集整理的一个非常奇怪的C++拷贝构造函数问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: UE4 C++与蓝图的继承问题
- 下一篇: UE4 材质:石缝提高混合权重