When to destroy, when not to destroy

Discussion in 'C++' started by Ook, Oct 11, 2005.

  1. Ook

    Ook Guest

    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];
     
    Ook, Oct 11, 2005
    #1
    1. Advertising

  2. Ook

    Guest

    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!
     
    , Oct 11, 2005
    #2
    1. Advertising

  3. Ook

    Ook Guest

    <> wrote in message
    news:...
    > 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 ;)
     
    Ook, Oct 11, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jimjim
    Replies:
    28
    Views:
    876
    Michael Wojcik
    Apr 14, 2004
  2. Replies:
    5
    Views:
    556
    James Kuyper
    May 25, 2009
  3. requinham
    Replies:
    11
    Views:
    2,256
    Michael Doubez
    Feb 19, 2010
  4. Jan
    Replies:
    4
    Views:
    94
  5. Eli
    Replies:
    0
    Views:
    124
Loading...

Share This Page