constructor question

J

junw2000

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

Thanks.

Jack
 
K

Kai-Uwe Bux

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
 
D

Daniel T.

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,151
Latest member
JaclynMarl
Top