我有一个类其具有构件:C++ 11复制的std ::的std ::的unique_ptr的载体,其为一个构件
std::vector<std::unique_ptr<layer>> _layers;
我明白的std::unique_ptr
性质是成非可复制。 我的graph::graph(const graph & rhs);
拷贝构造函数产生一个编译错误,因为我的普通实现违反了std::unique_ptr
的性质。
graph::graph(const graph & rhs)
: _layers(rhs._layers) {}
如果我做了std::move
那么我会违反PARAM rhs
的常量性,这不是我想要的。 我知道我可以制作深层副本(例如,为存储在rhs._layers
中的每个对象创建新的唯一指针),但是有没有一些优雅的方式来执行此操作,除了迭代每个项目并分配新的唯一指针?
GCC/G ++是C++ 11不是C++ 14
我目前的解决方案是深拷贝的对象和分配新指针:
graph::graph(const graph & rhs)
{
for (const auto & ptr : rhs._layers)
_layers.emplace_back(std::unique_ptr<layer>(new layer(*ptr)));
}
这已经在这里讨论过了:http://stackoverflow.com/questions/16030081/copy-constr uctor-for-a-class-with-unique-ptr –
未受教育的猜测:对于'shared_ptr's视图的'weak_ptr',这会是一个很好的用例吗? – Katana314
@ Katana314我不知道TBH,但这些指针不能在课堂以外看到或访问。我不介意复制对象(因此深层复制)。这种情况下'weak_ptr'的优点是什么? –