【发布时间】:2018-02-22 10:05:43
【问题描述】:
#include <iostream>
class Box{
public:
int x;
Box(){
x=0;
std::cout << "Constructor" << std::endl;
}
Box(const Box& other){
x = other.x;
std::cout << "Copy constructor" << std::endl;
}
Box(Box&& other){
x = other.x;
other.x = 0;
std::cout << "Move constructor" << std::endl;
}
Box& operator=(Box&& other) {
x = other.x;
other.x = 0;
std::cout << "Move assignment" << std::endl;
return *this;
}
Box& operator=(const Box &other){
x = other.x;
std::cout << "Copy assignment" << std::endl;
}
~Box(){
std::cout << "Destructor" << std::endl;
x=0;
}
};
Box send(Box b){
std::cout << "Sending" << std::endl;
return b;
}
int main(){
Box b1, b2;
b1 = send(b2);
return 0;
}
在输出中:
Constructor
Constructor
Copy Constructor
Sending
Move Constructor
Move Assignment
Destructor
Destructor
Destructor
Destructor
我不太清楚为什么在执行b1 = send(b2) 时使用移动构造函数然后赋值。
【问题讨论】:
-
你必须创建一个临时返回值。
-
我猜(不要引用我的话)这是因为你在发送函数中创建了一个 Box 的副本,因为它在离开函数范围时被删除,它调用移动赋值,因为返回值可以被视为右值。不过目前无法检查,这只是我的猜测
标签: c++