【发布时间】:2013-11-14 03:55:15
【问题描述】:
找不到太多关于 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() ) ) );
}
};
假设 class Graph 确实有一个复制构造函数:
Graph( const Graph & graph )
我不想让 this->_graph 指向/共享同一个对象! 相反,我希望 this->_graph 将对象从 state._graph 深复制到我自己的 this->_graph 副本中。 p>
上面的方法是正确的吗?
Documentation of std::make_shared 注意到:
此外,f(shared_ptr(new int(42)), g()) 会导致内存泄漏 如果 g 抛出异常。如果 make_shared 是,则此问题不存在 用过。
还有其他方法可以解决这个问题,更安全或更可靠吗?
【问题讨论】:
-
如果您希望每个对象指向自己的
Graph,是否有理由使用shared_ptr?似乎另一种指针类型会更合适,就像将Graph作为直接子对象一样。 -
是的,它们属于其他类。但是在这种特殊情况下,我真的需要一个副本,而不是像我打算更改它那样共享给定的对象,而不希望更改原始对象。你建议我改用 unique_ptr 吗?
-
这将是我的建议之一,但如果对象真的是共享的,那么还有很多其他好的方法。
标签: c++11 shared-ptr deep-copy