Skip to main content
GameDev.net gamedev.net
🔒 Locked

New throwing an exception

Started by Eriond Jan 2, 2004 at 9:51 AM 3 replies 300+ views
Original Post
Eriond
Eriond
I''m reading The C++ Standard Library right now and don''t understand this snippet:
class ClassB {
private:
    ClassA *ptr1;
    ClassA *ptr2;
public:
    //constructor that initializes the pointers will cause resource leak if second new throws

    ClassB(ClassA val1, ClassA val2) : ptr1(new ClassA(val1)), ptr2(new ClassA(val2)) {}
    //.........

};
Why would it only be a resource leak if the second new thorws and not the first one?
Null and Void
Null and Void
Nothing has been allocated yet if the first throws an exception. If the second throws something (std::bad_alloc), the first will have already allocated something and nothing is (yet) setup to clean up after that first allocation.

Eriond
Eriond
Oh, didn''t think about that, thank you.
Eriond
Eriond
I know, the example is in the chapter about auto_ptr to show why it is bad, I only asked why it was like that

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.