我的问题不同,因为我可能“知道”复制省略。我正在学习复制初始化。然而,下面的代码让我很困惑,因为我已经使用关闭了复制省略-fno-elide-contructors -O0
option.
#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++
确实在我之前的版本中关闭了优化。
So, why test instance = {1,2}
不调用复制构造函数或移动构造函数?临时对象不是通过隐式转换创建的吗?和instance
应该由该临时对象初始化吗?
why test instance = {1,2}
不调用复制构造函数或移动构造函数?
不应该。test instance = {1,2}
is 复制列表初始化 https://en.cppreference.com/w/cpp/language/list_initialization#Explanation,作为效果,适当的构造函数(即test::test(int, int)
) 用于构造对象instance
直接地。无需在此处构造临时并调用复制/移动构造函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)