Connecting Tech Pros Worldwide Help | Site Map

When to destroy, when not to destroy

  #1  
Old October 11th, 2005, 01:25 AM
Ook
Guest
 
Posts: n/a
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];


  #2  
Old October 11th, 2005, 01:55 AM
AnonMail2005@gmail.com
Guest
 
Posts: n/a

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!

  #3  
Old October 11th, 2005, 03:25 AM
Ook
Guest
 
Posts: n/a

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


Similar Threads
Thread Thread Starter Forum Replies Last Post
How to destroy an session Shun answers 1 October 20th, 2006 08:35 AM
How to destroy an object and all references to it vb.net Miguel Ribeiro answers 1 January 12th, 2006 10:55 PM
how to destroy array Sarfraz Hooda answers 2 November 16th, 2005 05:20 AM
something to destroy html steve answers 1 July 20th, 2005 11:49 AM