我正在尝试将unique_ptr与任何STL容器(实际上我更喜欢使用list)一起使用,我发现unique_ptr需要移动语义。 以下是一个示例代码,其中employee是基类:
typedef std::unique_ptr<employee> p_employee;
std::list<p_employee> make_test_array() {
std::list<p_employee> objects = {
p_employee(new accounter(...)),
p_employee(new engineer(...)),
p_employee(new developer(...))
};
return objects;
}
你看我想做什么 - 只是从函数中返回这个列表
那么有没有能力做到这一点?什么是正确的技术?
std::array
是一个聚合体,因此您可以使用大括号来执行初始化,就像您原始示例中的那样,因为在这种情况下它将是聚合初始化,并且不会尝试复制unique_ptr
。 或者,您可以在array
中默认构造unique_ptr
,然后使用unique_ptr::reset
或其移动赋值运算符添加元素 - http://coliru.stacked-crooked.com/a/9f71df479b4124f3 - Praetorian