470,870 Members | 1,404 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,870 developers. It's quick & easy.

new and memory management

Hi all:

When in a class constructor an exception is thrown, the class must free
memory it has reserved during initialization.
But what about the memory reserved for a class itself.

Ex:

MyClass* myObject;

try {
myObject = new MyClass();
} catch(excepcion& e) {
...
}

If the constructor of MyClass throws an exception, does new return
memory that must be freed?

Thanks in advance
Apr 20 '06 #1
3 1469
Carlos Martinez wrote:
When in a class constructor an exception is thrown, the class must free
memory it has reserved during initialization.
But what about the memory reserved for a class itself.


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

"In p = new Fred(), does the Fred memory "leak" if the Fred constructor
throws an exception?"

Always Google for the FAQ and such before posting!

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Apr 20 '06 #2
Carlos Martinez wrote:
Hi all:

When in a class constructor an exception is thrown, the class must free
memory it has reserved during initialization.
But what about the memory reserved for a class itself.

Ex:

MyClass* myObject;

try {
myObject = new MyClass();
} catch(excepcion& e) {
...
}

If the constructor of MyClass throws an exception, does new return
memory that must be freed?

Thanks in advance


The memory is freed so don't worry.

Regards,
Ben
Apr 20 '06 #3
Carlos Martinez wrote:
Hi all:

When in a class constructor an exception is thrown, the class must free
memory it has reserved during initialization.
But what about the memory reserved for a class itself.

Ex:

MyClass* myObject;

try {
myObject = new MyClass();
} catch(excepcion& e) {
...
}

If the constructor of MyClass throws an exception, does new return
memory that must be freed?

Thanks in advance


See also this FAQ:

http://www.parashift.com/c++-faq-lit...html#faq-11.14

which describes in gory detail what happens implicitly when you use
new, including when an exception is thrown by your object's
constructor.

Cheers! --M

Apr 20 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Richard Jones | last post: by
2 posts views Thread by DANIEL BEAULIEU J | last post: by
9 posts views Thread by Mike P | last post: by
1 post views Thread by trialproduct2004 | last post: by
3 posts views Thread by Jim Land | last post: by
9 posts views Thread by benoit808 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.