移动语义和unique_ptr

时间:2015-03-04 05:49:15

标签: c++ move-semantics unique-ptr

如何对使用unique_ptr的类执行移动操作?不将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;
};

1 个答案:

答案 0 :(得分:2)

你需要移动指针。

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