c++ - 为什么需要唯一指针中的 move 构造函数和 move 赋值构造函数?

标签 c++ c++11 smart-pointers move-semantics unique-ptr

我有一个unique_ptr 的简化示例。我想知道唯一指针中的 move 构造函数和 move 赋值运算符需要什么? 如果我正确理解 move 构造函数(并传递右值),这两行代码的结果应该相同。

UniquePointer<T> a(new T);
UniquePointer<T> a(UniquePointer<T>(new T));

下面是简化的 UniquePointer 代码:

template<typename T> class UniquePointer {
    T* m_ptr;
public:
    UniquePointer(const UniquePointer&) = delete;
    UniquePointer& operator=(const UniquePointer&) = delete;
    UniquePointer(UniquePointer&& rhs);
    UniquePointer& operator=(UniquePointer&& rhs);
    UniquePointer(T* ptr) : m_ptr(ptr) { }
    T* operator->() const { return m_ptr; }
    T& operator*() const { return *m_ptr; }
    T* get() const { return m_ptr; }
    ~UniquePointer() { delete m_ptr; }
};

最佳答案

首先调用常规构造函数UniquePointer(T* ptr)(不是 move 构造函数)。第二个调用 move 构造函数 UniquePointer(UniquePointer&& rhs),当你传入类型为 UniquePointer 的右值时,复制构造函数被删除。

当你这样做的时候你还需要 move 构造函数

UniquePtr<T> ptr = std::move(some_old_unique_ptr);

在这种情况下,您需要从旧的std::move,因为旧的是左值。在已经构造的对象上调用 move 赋值运算符

ptr = std::move(yet_another_ptr); // invokes the move assignment operator

至于为什么需要它们,那是因为设计。此类对象不可复制,因此您需要 move 它们。

关于c++ - 为什么需要唯一指针中的 move 构造函数和 move 赋值构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30402588/

相关文章:

c++ - 在 OpenGL 中绘制两个点云之间的交点

c++ - 在 QPixmap : aggregate 'QWidget w' has incomplete type and cannot be defined 上渲染 QGraphicsItem

c++ - 最小化浪费的字节以对齐 2 个 header 之间的数据(自定义分配器)

c++ - 为什么成员模板方法必须在类外使用 template<> 进行专门化

c++ - 可变字符模板的用户定义文字

c++ - 为什么 shared_ptr<void> 合法,而 unique_ptr<void> 格式不正确?

c++ - weak_ptr 和父子循环依赖

c++ - 关于引用指针的说明

multithreading - 读取另一个线程中的变量

c++ - 测试 std::pointer_traits 是否适用于我的类型