一个非常奇怪的C++拷贝构造函数问题
生活随笔
收集整理的这篇文章主要介绍了
一个非常奇怪的C++拷贝构造函数问题
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
编译环境:VS2022,C++14,对比测试如下:
测试一:
#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();//输出结果如下 //CTestA-contruct }通过该测试知道:CTestA oa = CTestA()这行代码导致了构造函数被调用,但拷贝构造函数并没有使用,operator=也没有被调用。
测试二:
#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();}该测试无法通过,编译错误如下
//1>E:\UETest\TestCPP\TestCPP.cpp(18,1): error C2280: “CTestA::CTestA(const CTestA &)”: 尝试引用已删除的函数。
这说明,编译时会尝试调用拷贝构造函数!
这就非常奇怪了,通过测试一我们知道拷贝构造函数不会被调用,而这里又证明它会被调用!
没搞明白这是怎么回事,猜想可能是编译时确实会调用拷贝构造函数,但运行时被优化掉了?
总结
以上是生活随笔为你收集整理的一个非常奇怪的C++拷贝构造函数问题的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: UE4 C++与蓝图的继承问题
- 下一篇: C++友元与输出运算符重载