c++11 - std::shared_ptr 深拷贝对象

标签 c++11 shared-ptr deep-copy

找不到太多关于 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/

相关文章:

c++ - 如何使用静态转换管理共享对象的生命周期?

c++ - 使用函数参数作为常量表达式的一部分 - gcc vs clang

c++ - 如何正确关闭使用 asio 进行事件排队的类实例

c++ - typedef 包含模板化类的共享指针

C++ 重载运算符、赋值、深度复制和加法

c++ - 如何在层次结构中实现运算符使用?

c++ - 使用 Auto 和 Lambda 处理信号?

inheritance - shared_ptr 返回一个接口(interface)

entity-framework-core - 如何在 EF Core 中进行深度克隆/复制

c# - 克隆 WPF 控件和对象层次结构