0

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?

Community
  • 1
  • 1
Deqing
  • 14,098
  • 15
  • 84
  • 131
  • Just on what you've shown, you're fine. You could explicitly declare those methods as '= default' to communicate you've done this knowingly. – codah Apr 17 '14 at 03:05
  • It depends on what you mean by "safe". In regards to memory leaks, double deletes, etc, then, yes, you are safe. If this class is to be used in a multithreaded environment, you've now introduced the possibility for subtle hidden shared, cross-thread state sharing that is unlocked, and not safe. – Nathan Ernst Apr 17 '14 at 06:00
  • Read up on the [rule of Zero](http://flamingdangerzone.com/cxx11/2012/08/15/rule-of-zero.html). – rubenvb Apr 17 '14 at 07:19

1 Answers1

0

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.

yizzlez
  • 8,757
  • 4
  • 29
  • 44