移动语义和 unique_ptr

move semantics and unique_ptr

如何对使用 unique_ptr 的 class 执行移动操作?将 unique_ptr 设置为 null 不会导致数据删除吗?如果我像这样通过 unique_ptr 的列表初始值设定项执行复制,数据会被保留还是删除?


template<typename T, typename A = std::allocator<T>>
class forward_list
{
...
private:
    struct node
    {
        T data;
        std::unique_ptr<T> next;
    };
    std::unique_ptr<node> root_;
    std::unique_ptr<node> leaf_;
    size_t count_;
    const A& heap;
};

// Move constructor. Constructs the container with the contents of other using move semantics.
// If alloc is not provided, allocator is obtained by move-construction from the allocator belonging to other.
inline forward_list(forward_list&& other)
 : root_(other.root_), leaf_(other.leaf_), count_(other.count_), heap(other.heap)
{
    other.root_ = nullptr;
    other.leaf_ = nullptr;
    other.count_ = 0;
};

您需要移动指针。

forward_list(forward_list&& other) :
    root_(std::move(other.root_)),
    leaf_(std::move(other.leaf_)),
    count_(other.count_),
    heap(other.heap)
{
    // Do nothing
}