【问题标题】:move semantics and unique_ptr移动语义和 unique_ptr
【发布时间】:2015-03-04 05:49:15
【问题描述】:

您将如何对使用 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;
};

【问题讨论】:

  • 您不必定义移动构造函数(除非forward_list 定义了其他未在此处显示的特殊成员函数)。编译器将生成一个移动构造函数,在这种情况下会做正确的事情(再次假设不存在您上面未显示的其他数据成员)。
  • 我相信 unique_ptr 已经与一般的移动语义类似。这意味着在您的代码分配给唯一指针的位置,这些指针已经为空,因为它们的内容已移至新指针。
  • @Praetorian 我已经定义(为简单起见,此处未显示)许多其他成员函数,包括为 stl forward_list 定义的所有成员函数。

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


【解决方案1】:

您需要移动指针。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-07
    • 2014-07-13
    • 2014-12-18
    • 1970-01-01
    • 2020-12-23
    • 2016-02-04
    • 2020-08-20
    • 2012-01-01
    相关资源
    最近更新 更多