0

When we define the copy constructor, is it required that we clear the contents of the object we are writing over? I am implementing a binary search tree, and wondering if I wouldn't have a memory leak unless I clean it up when implementing the copy constructor and the assignment operator.

fadmwo
  • 53
  • 5

3 Answers3

6

When we define the copy constructor, is it required that we clear the contents of the object we are writing over?

At time of construction there's no content that needs to be overwritten. Just make sure you're doing all of the copies of member variables in the constructor member initializer list, rather than doing in the constructor's body.

Otherwise the compiler would generate default initialization for members, and then there could be something allocated, that actually needs to be cleared and overwritten (or deep copied).

Especially if you're dealing with pointers as you claim to do.

Best you should follow The Rule of Three (Five) to ensure everything is done consistently.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
4

If a copy constructor is running, there is no "object we are writing over". You are creating ("constructing") a new object, from scratch, but copying data from some other object to populate its initial state.

For an assignment operator, yes this is definitely a consideration and you need to be sure to avoid leaks. Though, if you employ RAII so you don't have any manual memory management, then you have nothing to worry about. (Beyond that, I don't understand how pointers come into it.)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

As the others have stated, using the copy constructor will create a new object.
What you have to consider, tho:
If your original object is the owner of some other data e.g. foo* allocated with new or a shared_ptr, copying the object will simply copy the pointer and its adress.
You will not actually copy the owned data.
In case of a raw foo* and a delete foo in your destructor, the second object being destroyed will try to delete removed memory.

I3ck
  • 433
  • 3
  • 10