Your ideas give me much insights. Two more comments,
to care to free it. But for other types of resources, like file handler, I
release the resources if there are exceptions in constructor. Right? Any
On Dec 22, 11:37 am, ajk <a...@workmail.com> wrote:
On Fri, 21 Dec 2007 10:46:40 -0500, "Larry Smith"
<no_spam@_nospam.com> wrote:
it is normally not a good idea to do operations in the ctor that could
cause an exception. the reason for this is that if an exception is
ever thrown in your ctor you end up with an invalid object. therefore
it is better to have some other method to initialize such with and
handle a failure outside the ctor like bool init() or something.
That's completely false as Alex stated.
i forgot to add: the dtor is never called when ctor throws an
exception so the heck do you do the cleanup if the ctor has allocated
three different things?
please tell me since you obviously have such insight.
Destructor is not called for that particular class but it is called
for all the already initialized base objects, member objects, virtual
bases etc. If you are allocating 3 (or any number) of different things
- use smart pointers in constructors as in:
MyClass::MyClass()
{
std::auto_ptr<T1> autoptrT1(new T1);
std::auto_ptr<T2> autoptrT2(new T2);
std::auto_ptr<T3> autoptrT3(new T3);
//....
std::auto_ptr<TN> autoptrTN(new TN);
//auto_ptr release does not throw
//this is considering ptr* are simple pointers not smart ones
//if they are smart ones - their destructors will be called.
//if they are not members - the above works anyway.
ptrT1 = autoptrT1.release();
ptrT2 = autoptrT2.release();
ptrT3 = autoptrT3.release();
//...
ptrTN = autoptrTN.release();
}