Connecting Tech Pros Worldwide Help | Site Map

When to destroy, when not to destroy

 
LinkBack Thread Tools Search this Thread
  #1  
Old October 11th, 2005, 12:25 AM
Ook
Guest
 
Posts: n/a
Default When to destroy, when not to destroy

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, 12:55 AM
AnonMail2005@gmail.com
Guest
 
Posts: n/a
Default 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, 02:25 AM
Ook
Guest
 
Posts: n/a
Default 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 ;)


 

Bookmarks

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On

Popular Articles

What is Bytes?

We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights. Get the best answers to your questions from over 220,989 network members.