cuốn sách gpt4 ai đã làm

c++ - 为什么在设置对象等于另一个函数的返回值时调用移动构造函数/赋值

In lại Tác giả: Walker 123 更新时间:2023-11-28 01:36:51 30 4
mua khóa gpt4 Nike

#include 

class Box{
công cộng:
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;
trả lại *cái này;
}

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 chính(){
Box b1, b2;
b1 = send(b2);
trả về 0;
}

在输出中:

Người xây dựng
Người xây dựng
Copy Constructor
Sending
Move Constructor
Move Assignment
Destructor
Destructor
Destructor
Destructor

我不太清楚为什么在执行 b1 = send(b2) 时使用移动构造函数然后赋值。

câu trả lời hay nhất

Why is the move constructor/assignment called when setting an object equal to the return value of another function

của bạnsend 函数返回b,它是一个参数,而不是局部变量:

Box send(Box b) {
std::cout << "Sending" << std::endl;
return b; // b is a parameter
}

因此没有发生 RVO 优化,因为 returning a parameter disables RVO .同时,还有另一个可用的优化选项,隐式 std::di chuyển:

Box send(Box b) {
std::cout << "Sending" << std::endl;
return std::move(b); // implicit std::move is applied.
}

所以它是使用你的移动构造函数构建的:

Box(Box&& other);

如果您改为创建并返回局部变量 c,您将看不到移动构造:

Box send(Box b) {
Box c;
std::cout << "Sending" << std::endl;
return c; // Returns c, not b -> No move construction thanks to RVO
}

因为 RVO 随后跳入。

关于c++ - 为什么在设置对象等于另一个函数的返回值时调用移动构造函数/赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48924584/

30 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress