Francisco Aguilera
Francisco Aguilera

Reputation: 3482

move semantics and unique_ptr

How would you perform a move operation on a class that uses unique_ptr? Wouldn't setting the unique_ptr to null cause deletion of the data? If I perform a copy through a list initializer of the unique_ptr like so, would the data be preserved or deleted?


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;
};

Upvotes: 3

Views: 649

Answers (1)

James Adkison
James Adkison

Reputation: 9602

You need to move the pointer.

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

Upvotes: 3

Related Questions