std :: shared_ptr深层复制对象 [英] std::shared_ptr deep copy object
问题描述
在C ++ 11上找不到很多,只能在增强上使用。
Can't find much on that for C++11 but only on boost.
请考虑以下课程:
class State
{
std::shared_ptr<Graph> _graph;
public:
State( const State & state )
{
// This is assignment, and thus points to same object
this->_graph = std::make_shared<Graph>( state._graph );
// Deep copy state._graph to this->_graph ?
this->_graph = std::shared_ptr<Graph>( new Graph( *( state._graph.get() ) ) );
// Or use make_shared?
this->_graph = std::make_shared<Graph>( Graph( *( state._graph.get() ) ) );
}
};
假设 class Graph 确实具有副本构造函数:
Suppose class Graph does have a copy constructor:
Graph( const Graph & graph )
我不想让 this-> _ graph 指向/共享同一对象!
相反,我希望 this-> _ graph 将对象从 state._graph 复制到我自己的 this-> _ graph
I do not want to have this->_graph point/share the same object! Instead, I want this->_graph to deep copy the object from state._graph, into my own this->_graph duplicate.
上面的方法是否正确?
此外,如果g抛出异常,f(shared_ptr(new int(42)),g())可能导致内存泄漏
。如果使用了make_shared
,则不存在此问题。
Moreover, f(shared_ptr(new int(42)), g()) can lead to memory leak if g throws an exception. This problem doesn't exist if make_shared is used.
还有另一种解决方法,更安全或更安全
Is there another way of going about this, safer or more reliable?
推荐答案
如果要复制 Graph
复制对象时,始终可以定义副本构造函数和赋值运算符来做到这一点:
If you want to make a copy of the Graph
object when you make a copy of the object, you can always define your copy constructor and assignment operator to do just that:
State::State(const State& rhs) : _graph(std::make_shared(*rhs._graph)) {
// Handled by initializer list
}
State::State(State&& rhs) : _graph(std::move(rhs._graph)) {
// Handled by initializer list
}
State& State::operator= (State rhs) {
std::swap(*this, rhs);
return *this;
}
希望这会有所帮助!
这篇关于std :: shared_ptr深层复制对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!