我的问题不同,因为我可能“知道”复制省略。我正在学习复制初始化。但是,以下代码让我感到困惑,因为我已经使用 -fno-elide-contructors -O0 选项关闭了复制省略。
#include <iostream>
using namespace std;
class test{
public :
test(int a_, int b_) : a{a_}, b{b_} {}
test(const test& other)
{
cout << "copy constructor" << endl;
}
test& operator=(const test& other)
{
cout << "copy assignment" << endl;
return *this;
}
test(test&& other)
{
cout << "move constructor" << endl;
}
test& operator=(test&& other)
{
cout <<"move assignment" << endl;
return *this;
}
private :
int a;
int b;
};
test show_elide_constructors()
{
return test{1,2};
}
int main()
{
cout << "**show elide constructors**" <<endl;
show_elide_constructors();
cout << "**what is this?**" <<endl;
test instance = {1,2};//why neither move constructor nor copy constructor is not called?
cout << "**show move assignment**" <<endl;
instance = {3,4};
return 0;
}
我首先使用命令构建:
g++ -std=c++11 -fno-elide-constructors -O0 main.cpp -o main 得到如下结果:
**show elide constructors**
move constructor
**what is this?**
**show move assignment**
move assignment
然后我使用不带 -fno-elide-constructor -O0 选项的命令进行构建,以证明 g++ 确实在我之前的构建中关闭了优化。
那么,为什么 test instance = {1,2} 不调用复制构造函数或移动构造函数?不是从隐式转换创建的临时对象吗? instance 应该由那个临时对象初始化吗?
最佳答案
why
test instance = {1,2}does not call copy constructor or move constructor?
不应该。 测试实例 = {1,2} 是 copy-list-initialization ,作为效果,适当的构造函数(即 test::test(int, int))用于直接构造对象 instance。无需在此处构造临时并调用复制/移动构造函数。
关于c++ - 复制初始化: why move or copy constructor was not called even if copy-elision is turned off?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51257847/