When to destroy, when not to destroy

O

Ook

I was taught that in a copy constructor, you don't have to destroy[] your
arrays, but in an overloaded assignment operator, you have to. Example:

When do you delete[], and when do you not? Is it arbitrary, or are there
general guidelines that should be followed? I'm thinking that in the copy
constructor, you are creating a new instance of the class, and in the
assignment, you have already created the class and therefore have to
destroy[] before you new. Is this correct?

// Copy constructor
_data = new int[ _size ];

// Overloaded Assignment operator:
delete [] _data;
_data = new int[_size];
 
A

AnonMail2005

I'm thinking that in the copy
constructor, you are creating a new instance of the class, and in the
assignment, you have already created the class and therefore have to
destroy[] before you new. Is this correct?

This is 100% correct. There is nothing to clean up in a copy
constructor.

The other thing you need to do in an assignment operator (and not in
any constructor) is to check for self assignment. In the above
example, if you don't check for this, you will have deleted your data!
 
O

Ook

I'm thinking that in the copy
constructor, you are creating a new instance of the class, and in the
assignment, you have already created the class and therefore have to
destroy[] before you new. Is this correct?

This is 100% correct. There is nothing to clean up in a copy
constructor.

The other thing you need to do in an assignment operator (and not in
any constructor) is to check for self assignment. In the above
example, if you don't check for this, you will have deleted your data!

Yeah, I got that - I omitted that part of the code for the sake of
simplicity. Glad I 'm on the right track ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top