5

Possible Duplicate:
What is The Rule of Three?

When you require to define to your own assignment operator?

Community
  • 1
  • 1
user963241
  • 6,758
  • 19
  • 65
  • 93

1 Answers1

12

Generally, you'll need to define your own assignment operator under the same circumstances when you need to define your own copy constructor - i.e. when a default copy won't cut it. This happens in cases when your object manages dynamically allocated memory or other resources which need to be specially copied.

For example, if you have a class which manages a pointer that points to dynamically allocated memory, the default assignment operator will simply copy the pointer. Generally, this is not what you want - you want each object instance to have its own internal copy of the allocated data, and so you'll need a special assignment operator that allocates its own memory and performs a copy. This is, for example, what std::vector needs to do when copied or assigned.

Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
  • Yes, managing dynamic memory was my guess. – user963241 Jan 22 '11 at 23:50
  • 3
    @cpx: In fact it is a little more general: managing any type of resource for which the default constructor won't do it correctly or is not available. That includes memory held by pointers, but also any other resource like for example a `mutex` – David Rodríguez - dribeas Jan 23 '11 at 00:05