By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,949 Members | 884 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,949 IT Pros & Developers. It's quick & easy.

ctor exception question

P: n/a
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?

Apr 15 '06 #1
Share this Question
Share on Google+
7 Replies


P: n/a
Thomas wrote:
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.

Apr 15 '06 #2

P: n/a

Thomas wrote:
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?


No, see:
http://www.parashift.com/c++-faq-lit...html#faq-16.10

Abdo Haji-Ali
Programmer
In|Framez

Apr 15 '06 #3

P: n/a
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)?
}

Apr 15 '06 #4

P: n/a

bb wrote:
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.

Apr 15 '06 #5

P: n/a
bb
Thanks Maxim. Thats a v.good idea and works.

Apr 16 '06 #6

P: n/a

bb wrote:
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.

Apr 16 '06 #7

P: n/a
bb
Thanks again Maxim. I do appreciate those important points.

Apr 16 '06 #8

This discussion thread is closed

Replies have been disabled for this discussion.