找不到太多关于 C++11 的内容,只能找到关于 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() ) ) );
}
};
假设类 Graph 确实有一个复制构造函数:
Graph( const Graph & graph )
我不想让this->_graph点/共享同一个对象! 相反,我希望 this->_graph 将对象从 state._graph 深度复制到我自己的 this->_graph 副本中。
上面的方法是正确的方法吗?
Documentation of std::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.
还有其他更安全或更可靠的方法吗?
最佳答案
如果您想在复制 Graph 对象时复制该对象,则始终可以定义复制构造函数和赋值运算符来执行此操作:
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;
}
希望这有帮助!
关于c++11 - std::shared_ptr 深拷贝对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19969260/