【发布时间】: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