如何用智能指针编写一个类?

时间:2014-04-17 02:31:38

标签: c++ c++11 shared-ptr smart-pointers

假设我有一个班级:

class State {
  std::shared_ptr<Graph> _graph;
public:
  State():_graph(new Graph){}
};

关于rule of three,显然不需要在析构函数中释放_graph,因为它是一个智能指针。问题是,我是否需要为它编写复制构造函数和赋值运算符?

考虑以下事项:

State s1;
State s2 = s1;

第二行会发生什么?

看起来它会是s2._graph = s1._graph;,指针共享,所以我们安全吗?

1 个答案:

答案 0 :(得分:0)

默认生成的副本ctors和赋值运算符使用类成员中提供的那些。

shared_ptr copy constructor“分享对象的所有权”。

shared_ptr assignment operator取代并分享。

如果这是您想要的行为,则无需显式声明copy ctor和赋值运算符。