ctor exception question

T

Thomas

I have a class foo whose ctor might throw an exception. When I create a foo
object using "foo* myfoo = new foo;", and the ctor throws an exception, do
I need to delete myfoo to free its memory?
 
M

Maxim Yegorushkin

Thomas said:
I have a class foo whose ctor might throw an exception. When I create a foo
object using "foo* myfoo = new foo;", and the ctor throws an exception, do
I need to delete myfoo to free its memory?

The compiler will generate code that will deallocate the memory using
operator delete() if the constructor throws.
 
B

bb

However, in the following code... how to ensure "classA* ca" memory is
not leaked?

#include <iostream>

class classA {
public:
classA() { std::cout << "classA ctor." << std::endl; }
~classA() { std::cout << "classA dtor." << std::endl; }
private:
};

class classB {
public:
classB() {
throw "oops";
std::cout << "classB ctor." << std::endl;
}
~classB() { std::cout << "classB dtor." << std::endl; }
private:
};

class classD {
public:
classD() : ca(new classA), cb(new classB) {
std::cout << "classD ctor." << std::endl;
}
~classD() {
std::cout << "classD dtor." << std::endl;
delete cb;
delete ca;
}
private:
classA* ca;
classB* cb;
};

int main(int argc, char** argv) {

classD cd;

// code continues...
// how to release "classA* ca" in classD object (in cd above)?
}
 
M

Maxim Yegorushkin

bb said:
However, in the following code... how to ensure "classA* ca" memory is
not leaked?

Use std::auto_ptr<> or one of the boost smart pointers rather than
plain pointers. When any part of construction throws, the destructors
of so far constracted members and base classes are called.
 
M

Maxim Yegorushkin

bb said:
Thanks Maxim. Thats a v.good idea and works.

With a caveat: when using std::auto_ptr<> as a member don't forget to
disable copying by declaring the copy constructor and the assignment
operator non public or implement deep copy. Just declaring
std::auto_ptr<> member const prohibts copying as well.
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top