Re: Why it is not good code for constructor




"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

  • Why it is not good code for constructor
    ... Here is a sample from Dr. Dobb C++. ... (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 ...
    (microsoft.public.vc.language)
  • Re: Why it is not good code for constructor
    ... If, suppose, the base classes are constructed in B, A order, then if ... if bad_alloc is thrown in new int[], we just catch it and write some ... (I do not agree that there is resource leak, ... now if new intcompletes ok, but the constructor for A throws, the ...
    (microsoft.public.vc.language)
  • Re: Problem with linker
    ... but to have actually written a default constructor. ... such as overloading on int and pointer types. ... conversion of 0 to CString requires a user-defined conversion, ... acceleration operator *(distance d, time_squared t2); ...
    (microsoft.public.vc.mfc)
  • FAQ Suggestions
    ... It can only be applied to reference type variables converting to ... The .NET runtime can't guarantee that parameterless constructors will be ... performing by not having to call constructor code. ... number like casting an int to short) are always explicit. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Languages for embedded
    ... calling constructors of the structure's members. ... If I want to know whether xyz had a constructor, ... On the other hand, if I have a C struct xyz, and the API provides a ... If function ftakes an int by value, it can't modify any int value ...
    (comp.arch.embedded)

Loading