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

标签 c++ oop c++11

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

#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/

相关文章:

Javascript Freecodecamp "Do not use a Boolean as a Constructor"

php - 如何在代码中使用 PHP Namespace

c++ - 为什么我们需要引用折叠规则

C++ - 使用 opencv flann 寻找最近的邻居

c++ - 将 auto_ptr 传递给需要常量引用 auto_ptr 的函数有什么危险?

c# - 除了 SCSS 注入(inject)还有其他选择吗? (又名穷人通过默认构造函数注入(inject))

c++ - 将函数传递给模板

c++ - 自定义 C++ 预处理器/Typeful 宏

c++ - 移动设备上的 OpenGL vector 图形渲染性能

c++ - std::unique_ptr::get 有什么意义