首页 文章

std :: shared_ptr深层复制对象

提问于
浏览
11

C11上找不到多少,但仅限于提升 .

考虑以下课程:

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注意到:

此外,如果g抛出异常,f(shared_ptr(new int(42)),g())可能导致内存泄漏 . 如果使用make_shared,则不存在此问题 .

还有另一种方法可以解决这个问题,更安全或更可靠吗?

1 回答

  • 9

    如果要在复制对象时复制 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;
    }
    

    希望这可以帮助!

相关问题