复制构造函数 - 了解问题
Copy constructor - Understanding problems
我在理解复制构造函数C++有一些问题,希望有人可以帮助我。
据我所知,当函数返回类的实例时,会调用复制构造函数(除其他外)。
#include <iostream>
using namespace std;
class Test
{
int a;
public:
Test(int a) : a(42)
{}
// Copy constructor
Test(const Test& other)
{
cout << "copy constructor" << endl;
}
};
Test test_function()
{
Test a(3);
return a;
}
int main()
{
test_function();
return 0;
}
那么,如果我执行此代码,则永远不会调用复制构造函数?为什么?哪个对象比返回?
此外,如果我更换行
test_function();
自
Test b = test_function();
复制构造函数既不调用 - 为什么不呢?
提前致谢
编辑:将函数更改为:
Test test_function()
{
Test a(3);
Test b(34);
if (4 < 2)
return a;
else
return b;
}
可以看到复制构造函数调用,因为编译器无法使用 RVO。
它是(复制/移动)构造函数省略作为优化,以避免不必要的复制/移动。可以应用的另一个优化是完全忽略返回任何内容,因为您根本没有使用返回值。
无论如何,您可以禁用此优化,并查看此编译器开关 (gcc) 所需的消息:
-fno-elide-constructors
但是,仅将上面的开关用于测试,并让优化应用于实际程序。
Test test_function()
{
Test a(3);
return a;
}
此函数声明 Test
的本地副本并将其返回。 编译器将看到这一点,意识到它将在创建新副本时销毁本地副本,并简单地将本地副本省略到结果中。 要查看您想要的结果,这可能会更好:
Test test_function(const Test& t)
{
return t;
}
int main()
{
Test t1;
Test t2 = test_function(t1);
return 0;
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- Rand() 没有显示随机数,请帮助我了解出了什么问题:)
- 问题是关于C 的数组,以便在编程主题中有更多的了解
- 关于了解C++线程"detach()"的问题
- 复制构造函数 - 了解问题
- 了解 DXGI DirectX 11 桌面复制以获取缓冲区或阵列的问题
- 了解指针和'new'如何工作的问题
- 试图了解我的泡沫排序方法有什么问题
- 了解双指针的问题并将其传递给函数
- 我有一个问题,了解如何与队列工作