Connecting Tech Pros Worldwide Forums | Help | Site Map

When to destroy, when not to destroy

Ook
Guest
 
Posts: n/a
#1: Oct 11 '05
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];



AnonMail2005@gmail.com
Guest
 
Posts: n/a
#2: Oct 11 '05

re: When to destroy, when not to destroy


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!

Ook
Guest
 
Posts: n/a
#3: Oct 11 '05

re: When to destroy, when not to destroy



<AnonMail2005@gmail.com> wrote in message
news:1128991578.438905.109520@g47g2000cwa.googlegr oups.com...[color=blue]
> 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!
>[/color]

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


Closed Thread