I got a question for a basic C++ question.

Started by
22 comments, last by kenjin 20 years, 10 months ago
quote:Original post by PantherBoy
One thing that catches some people out is that if an exception is thrown in an objects constructor, the destructor will NOT be called - therefore presenting you with a possible memory leak.


edit: I've just realised you mean the class destructor won't be called and if that is where the dynamic resources are deallocated then they won't be. However if you are using RAII then there won't be a problem.

Check out gotw and search the page for 'exception' articles. Here's one to get you started (although you may need to look at earlier ones to learn about strong/neutral exception safety). Start from the bottom (oldest). There are also other articles such as this one: To New, Perchance To Throw

[edited by - petewood on June 20, 2003 4:23:30 AM]
Advertisement
quote:Original post by SpaceRogue
I''m just a beginner, and I can see what Sneftel and Fruny are saying about the purpose of having constructors in the first place. However I just want to say that I have seen it suggested in at least one book to do it like the A.P. said for the same reasons he gives.

If you search hard enough, you will find support for just about any technique, regardless of the worthiness of the technique. Some people feel comfortable using a technique with the knowledge they are not alone. Unfortunately, popular support is insufficient criteria. Its not that simple.
Personally, I''d admit that separate setup functions are probably a good idea for many programmers. Doing everything in constructors means you have to be careful about the order of construction, and need to make everything exception-safe, which then often means using a load of smart pointers, and then a lot of try-catch blocks, some appropriate exception classes, constructor initialisation lists, etc. These are all non-trivial issues and there''s very little chance that any but an expert programmer will get it 100% right. For someone more used to languages like C or BASIC, the separate initialiser will be easier for them to get right.

[ MSVC Fixes | STL Docs | SDL | Game AI | Sockets | C++ Faq Lite | Boost
Asking Questions | Organising code files | My stuff | Tiny XML | STLPort]
quote:Original post by SabreMan
If you search hard enough, you will find support for just about any technique, regardless of the worthiness of the technique. Some people feel comfortable using a technique with the knowledge they are not alone. Unfortunately, popular support is insufficient criteria. Its not that simple.


I agree. I was just mentioning it...

I''ve been reading up on constructors that throw exceptions after seeing this thread and I want to learn to do it that way. I just wish I understood exceptions better.

This topic is closed to new replies.

Advertisement