问题描述
我写了一个程序,如下:
I wrote a program as below:
#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上对其进行了编译.输出为:
I compiled it on my Mac OS. The output is:
copy constructor
copy constructor
copy assignment
move assignment
我的问题是:
- 为什么
A a4 = foo();
的输出为空?我认为它应该调用move构造函数. - 为什么
A a3 = a2;
的输出是copy constructor
而不是copy assignment
?
- Why the output of
A a4 = foo();
is empty? I thought it should call the move constructor. - Why the output of
A a3 = a2;
iscopy constructor
instead ofcopy assignment
?
推荐答案
-
因为如果愿意,编译器可能会忽略复制和移动.相关的构造函数必须仍然存在,但是在标准中明确指出它们可能不会被调用. (这是标准定义的优化的罕见示例,特别是还允许将返回值优化也定义为标准定义.)
Because copies and moves may be elided by the compiler if it wishes. The relevant constructor must still exist, but it is explicitly stated in the standard that they might not be invoked. (This is a rare example of a standard-defined optimisation, in particular allowing Return Value Optimisation to be standard-defined also.)
因为在初始化中使用=
会执行构造操作,而不是分配操作.这就是语法,这有点令人困惑.在本质上,A a3(a2)
在本质上是等效的.
Because the use of =
in initialisation performs construction, not assignment. It's somewhat confusing that this is the syntax. A a3(a2)
, which is [essentially] equivalent, would be clearer in this regard.
这篇关于移动语义并复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!