gpt4 book ai didi

c++ - 谁负责释放由 std::move 移动的资源?

转载 作者:太空狗 更新时间:2023-10-29 19:40:11 26 4
gpt4 key购买 nike

考虑下面崩溃的简单代码:

#include <iostream>

struct test
{
int *x;
test(){ x = new int;}
~test(){delete x;}
};
int main() {
test x;
test y = std::move(x);
return 0;
}

我的问题是,当对象的资源被 std::move 移动时,当它的析构函数被调用作为对象超出范围的自然过程时会发生什么?这是否意味着我们不应该为堆栈上的对象调用 std::move

最佳答案

Does that mean we should not call std::move for object on stack?

不,这意味着您应该提供一个移动构造函数,它将 x 设置为 null。

请注意,在您的案例中没有默认的移动构造函数,因为您定义了自己的析构函数(ref)。

PS:不要忘记 rule of 5 .

关于c++ - 谁负责释放由 std::move 移动的资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50684725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com