-
Leaving constructor
Here is a class
Code:
class MyClass{
private:
SomeClass* sc;
public:
MyClass()
{
sc=new SomeClass;
}
};
when we create an object of the Class MyClass by caling new, 1st new will allocate memory for the class.Then the constructor of MyClass will be called.Inside it, constructor of Someclass will be called.If constructor of SomeClass fails what will happen to memory allocated to MyClass object.Leak or not?
Thanks in adv. for reply with regards,
-A
-
If the constructor of SomeClass throws an exception, then new should do a deallocation of the raw memory (SomeClass instance was never constructed) and rethrow the exception. All in all, no memory leak.
If MyClass allocates more than one object, it would be its job to catch the exception, deallocate the successfully created instances (and rethrow the exception). But then, if you have more than one pointer in a class, making the class exception-safe gets really hard (use smart pointers).
-