I have a class graph
which has a member:
std::vector<std::unique_ptr<layer>> _layers;
I understand that the nature of std::unique_ptr
is to be non-copyable.
My graph::graph(const graph & rhs);
copy constructor produces a compilation error, because my ordinary implementation violates the nature of std::unique_ptr
.
graph::graph(const graph & rhs)
: _layers(rhs._layers) {}
If I do a std::move
then I will be violating the constness of param rhs
, which is not what I want.
I know I can make deep copies (e.g., create new unique pointers for each object stored in rhs._layers
) but is there some elegant way of doing this, other than iterating each item in rhs._layers
and allocating a new unique pointer?
gcc/g++ is c++11 not c++14
My current solution is deep copying the objects and allocating new pointers:
graph::graph(const graph & rhs)
{
for (const auto & ptr : rhs._layers)
_layers.emplace_back(std::unique_ptr<layer>(new layer(*ptr)));
}