constructor question

Discussion in 'C++' started by junw2000@gmail.com, Jul 23, 2006.

  1. Guest

    I allocate memory in a constructor of my class. If the constructor
    crashes, how to recollect the resource, i.e., deallocate memory?

    Thanks.

    Jack
     
    , Jul 23, 2006
    #1
    1. Advertising

  2. Kai-Uwe Bux Guest

    wrote:

    > I allocate memory in a constructor of my class. If the constructor
    > crashes, how to recollect the resource, i.e., deallocate memory?


    A typical idiom is to use std::auto_ptr for that purpose:


    #include <utility>
    #include <iostream>

    struct A {

    int num;

    A ( int n )
    : num ( n )
    {}

    ~A ( void ) {
    std::cout << num << " destroyed properly.\n";
    }

    };

    struct X {

    A * a_ptr;
    A * b_ptr;

    X ( void ) {
    std::auto_ptr< A > a_helper ( new A ( 1 ) );
    std::auto_ptr< A > b_helper ( new A ( 2 ) );

    throw 2;

    a_ptr = a_helper.release();
    b_ptr = b_helper.release();
    }

    };

    int main ( void ) {
    try {
    X dummy;
    }
    catch ( ... ) {}
    }



    Best

    Kai-Uwe Bux
     
    Kai-Uwe Bux, Jul 23, 2006
    #2
    1. Advertising

  3. Daniel T. Guest

    In article <>,
    wrote:

    > I allocate memory in a constructor of my class. If the constructor
    > crashes, how to recollect the resource, i.e., deallocate memory?


    Crashes? If the constructor throws an exception, you are going to have
    to catch it, deallocate your memory, and then re-throw the exception.
     
    Daniel T., Jul 23, 2006
    #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. Giulio
    Replies:
    9
    Views:
    1,047
    Patrick Kowalzick
    Jun 25, 2003
  2. Brett Irving
    Replies:
    3
    Views:
    3,337
    John Harrison
    Jun 29, 2003
  3. lallous
    Replies:
    5
    Views:
    8,828
    David Harmon
    Jan 23, 2004
  4. Replies:
    6
    Views:
    510
  5. Generic Usenet Account
    Replies:
    10
    Views:
    2,248
Loading...

Share This Page