简体   繁体   中英

How to write a class with smart pointer?

Suppose I have a class:

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

With regards to rule of three , apparently no need to free _graph in destructor as it is a smart pointer. The question is, do I need to write copy constructor and assignment operator for it?

Considering following:

State s1;
State s2 = s1;

What will happen with the second line?

Looks like it will be s2._graph = s1._graph; , pointer shared, so we are safe?

Default generated copy ctors and assignment operators use the ones provided in the class members.

The shared_ptr copy constructor "shares ownership of the object".

The shared_ptr assignment operator replaces and shares.

If this is the behavior you want, their is no need to explicitly declare the copy ctor and the assignment operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM