【发布时间】:2020-12-30 07:40:09
【问题描述】:
我们知道 std::move does not actually move anything。它只是将左值引用 (&) 转换为右值引用 (&&)。
那么在下面的例子中,拷贝构造函数是如何被调用的呢?如果没有移动构造函数,构造使用 std::move() 的对象如何回退到复制构造函数?变量b 的这种绑定究竟是如何发生的?
struct Test {
// Default constructor
Test() {
std::cout << "Constructor is called." << std::endl;
mValue = 0;
}
// Copy constructor
Test(const Test& rhs) {
std::cout << "Copy Constructor is called." << std::endl;
mName = rhs.mName;
mValue = rhs.mValue;
}
std::string mName;
int mValue;
};
int main() {
Test a;
Test b = std::move(a);
return 0;
}
输出:
Constructor is called.
Copy Constructor is called.
【问题讨论】:
-
因为如果没有更好的候选者,右值引用可以被强制为 const 左值引用,这就是发生的事情。
-
一个 const 左值引用可以绑定到一个右值。这可以追溯到 C++11 之前的规则。
标签: c++ c++11 move-semantics