tags:

views:

86

answers:

3

Hi all

When the class with a member which is a pointer, we need implement a copy constructor for it. I have a question, if we have implemented a copy constructor, should we implement an assignment constructor too?

Best Regards,

+7  A: 

It is not called an assign constructor but rather an assignment operator, and yes you should. The rule of thumb is: if you need to write a destructor then you should also provide a copy constructor and assignment operator (or block the compiler from generating one)

David Rodríguez - dribeas
+1 for mentioning "blocking compiler from generating one". It is always an option.
SadSido
The rule of thumb, which is quite old, should not be taken literally in both directions. There are circumstances where you should write copy constructor and assignment operator and you don't have to write a destructor manually --but destruction is non-trivial none the less.
David Rodríguez - dribeas
+2  A: 

Another option here is using some smart pointer, appropriate to your tasks. By choosing the right smart pointer you can rely on compiler-generated destructor, copy constructor and an assignment operator (and write none of your own)...

SadSido
Smart pointers help in dealing with destruction, not construction. Consider a class that holds a datum through a (smart) pointer. A `shared_ptr` will help you release the datum only once (when the last reference goes out of scope), so destruction is fine. The problem is that a change in the copy will affect the original --the copy will be shallow.
David Rodríguez - dribeas
Good point. Anyway, I can imagine a smart pointer, that makes a copy of the object when the pointer itself is being copied. That is why I mention "appropriate for your tasks"... =)
SadSido
A: 

Whenever a class has a member variable to which memory is dynamically allocated, one should always implement following

  1. Copy Constructor
  2. Assignment Operator
  3. Destructor

Note : If the pointer variable is static, then no need to have all these.

Pardeep
Not just memory. If the class is responsible for managing any kind of resource, it should implement those three. (or declare them `private:`)
MSalters