i currently am throwing an exception in my constructor of my class and i read that when u do such a thing, the objects destructor is never called! meaning if i allocate any memory without using the heap, i have to MANUALLY deallocate the memory myself. An article i read stated using "resource allocation is initialization" can be used to solve this problem and is a must. I'm curious if anyone could give an example or any more usefull information on this topic! it's hard for me to understand and i'm not sure if i'm understanding it fully! -thx

An example may help.

Code that does not use RAII:

struct M
{
    M() ; // may throw! 
    // ...
};

struct A
{
    A( const char* s, const char* path ) ;
    ~A() ; // required

    // ...
        
    private:
       char* cstr ;
       FILE* file ;
       M* ptr_m ;

       void init() ; // may throw!
};

A::A( const char* s, const char* path ) :
       cstr( new char[std::strlen(+1)] ),
       file( std::fopen( path, "r+t" ) ),
       ptr_m( new M ) // *** what happens if M::M() throws?
                      // cstr won't be deleted, file won't be closed
{
    std::strcpy( cstr, s ) ;
    init() ; // *** what happens if init() throws?
             // ptr_m and cstr won't be deleted, file won't be closed
}

A::~A()
{
    delete ptr_m ;
    std::fclose(file) ;
    delete [] cstr ;
}

// etc.

Code that uses RAII:

struct M
{
    M() ; // may throw!
    // ... 
};

struct A
{
    A( const char* s, const char* path ) ;
    // no need to write destructor

    // ...
    
    private:
       std::string str ;
       std::ifstream file ;
       std::tr1::unique_ptr<M> ptr_m ;

       void init() ; // may throw!
};

A::A( const char* s, const char* path ) :
       str(s), file( path, std::ios::in|std::ios::out ),
       ptr_m( new M ) // *** don't care if M::M() throws;
                      // destructors of file and str will be executed 
{
    init() ; // *** don't care if init() throws;
             // destructors of ptr_m, file and str will be executed 
}

// etc
This article has been dead for over six months. Start a new discussion instead.