Re: Why it is not good code for constructor



Thanks for your advice, Ben!


I think if new int[] success and there are some other places in constructor
B which causes exception, then in the catch block of B's constructor, we can
use delete[] to free memory and rethrow the exception.

Do you think it is a good approach?


regards,
George

"Ben Voigt [C++ MVP]" wrote:


"George" <George@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:75F1E950-242F-46F3-9500-5BAA7FAC2AB6@xxxxxxxxxxxxxxxx
Hello everyone,


Here is a sample from Dr. Dobb C++. In the analysis, the code is bad
below.

But I do not think the code is bad,

1. if bad_alloc is thrown in new int[], we just catch it and write some
log;
2. if there are any exception in B's constructor, we will also be in catch
block and we could also write some log.

Why it is bad code? Any comments?

(I do not agree that there is resource leak, since if we met with
bad_alloc
in new int[], there is no memory allocated at all, so no root of
memory/resource leak).

The code you provided isn't sufficient to guarantee that.

What if:

class C : public B, public A
{
...
};

now if new int[n] completes ok, but the constructor for A throws, the array
is leaked with no chance to free it.



http://www.ddj.com/cpp/184401297

[Code]
C::C(int)
try
: B(new int[n]) // horrible!
{
...
}
catch(Error &e)
{

}
[/Code]



thanks in advance,
George



.



Relevant Pages

  • Re: new keyword
    ... Call constructor for object placed into allocated memory ... If an exception is thrown from the constructor, handle it, cleanup ... re-throw the exception up the stack. ... instantiate one in an available subblock. ...
    (microsoft.public.vc.mfc)
  • Re: Allocators and exceptions
    ... of an object never propagates an exception, ... I guess I had misunderstood what's meant by 'constructor', ... the leak in this case doesn't bother me too much, ... very long-running applications are likely to have problems with memory ...
    (comp.lang.ada)
  • Re: is such exception handling approach good?
    ... here if you get a memory exception in m_pConn you get a memory leak in ... m_pBuff since the dtor will not be called. ... has been created you can't clean it up in your exception handler. ... of them in constructor; sometimes all of them. ...
    (microsoft.public.vc.language)
  • Re: new keyword
    ... all required memory (what happens or which exception is thrown depends ... configured to have "new" return NULL if it fails to allocate. ... by the underlying object's constructor will be destructed, ... memory allocated by "new" will be freed. ...
    (microsoft.public.vc.mfc)
  • Re: exiting a constructor early
    ... what exactly happens to any dynamically allocated memory that was ... | obtained before the exception was thrown? ... but for memory that your object attempts to allocate in the constructor, ... you would have to somehow handle that memory in an appropriate handler, ...
    (alt.comp.lang.learn.c-cpp)