移动语义并复制构造函数
Move semantics and copy constructor
我写了一个程序,如下所示:
#include <iostream>
using namespace std;
class A {
public:
A() {
}
A(A &a) {
id = a.id;
cout << "copy constructor" << endl;
}
A& operator=(A &other) {
id = other.id;
cout << "copy assignment" << endl;
return *this;
}
A(A &&other) {
id = other.id;
cout << "move constructor" << endl;
}
A& operator=(A &&other) {
id = other.id;
cout << "move assignment" << endl;
return *this;
}
public:
int id = 10;
};
A foo() {
A a;
return a;
}
int main()
{
A a;
A a2(a); // output: copy constructor
A a3 = a2; // output: copy constructor
a3 = a2; // output: copy assignment
A a4 = foo(); // output:
a4 = foo(); // output: move assignment
return 0;
}
我在我的Mac OS上编译了它。输出为:
copy constructor
copy constructor
copy assignment
move assignment
我的问题是:
- 为什么
A a4 = foo();
的输出为空?我认为它应该调用移动构造函数。 - 为什么
A a3 = a2;
的输出是copy constructor
而不是copy assignment
?
-
因为如果编译器愿意,它可以省略副本和移动。相关构造函数必须仍然存在,但在标准中明确声明可能不会调用它们。(这是标准定义优化的罕见示例,特别是允许返回值优化也由标准定义。
-
因为在初始化中使用
=
执行构造,而不是赋值。这是语法有点令人困惑。A a3(a2)
,[基本上]等同,在这方面会更清楚。
编译器正在为以下对象生成默认方法:
A (const A &);
A & operator = (const A &);
如果将const
限定符添加到复制 ctor/assign 方法中,您可能会看到预期的结果。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类