Re: Are throwing default constructors bad style, and if so, why?
Andre Kaufmann wrote:
Mathias Gaunard wrote:
On 18 sep, 23:28, Andre Kaufmann <akfmn...@t-online.de> wrote:
c) How many developers expect constructors to throw ?
Any one that ever heard about RAII, exceptions, STL or modern C++?
(pick one)
So all code is written in modern C++ and all existing C++ code is 100%
exception safe ? At least my experience is that the world isn't perfect
and RAII and "modern C++" isn't that common as it should be.
I tend to initialize and use resources as late as possible.
Therefore I don't have commonly the need to allocate resources and
handle errors in the constructor anyways.
Then you're really missing the whole point of constructors, I guess.
They're made to initialize. If you want delayed initialization, just
delay construction.
Perhaps there's a difference between initialization of variables /
states and the initialization / acquisition of resources ?
Also, you're paying an extra overhead, since your object can always be
in a "non-initialized-yet" state, which means your invariant really
isn't what it ought to be.
Examples:
- The default constructor of an vector for example doesn't IIRC allocate
any memory.
- Why should an object which handles bitmaps allocate any bitmap
resources if it doesn't know the dimensions of the bitmap anyway ?
I walk along the same reasoning myself. A default-constructed, empty
container should not automatically assume I'll need to fill it right
away and be eager to preallocate (and refuse to even come into existence
if it can't right then and there)! This is quite clearly a design mistake.
But the example with the mutex makes a very strong counter-argument,
particularly since safely initializing lazily a mutex is not an easy
task itself. On the other hand, I don't feel that if I just create a
mutex (e.g. as a member) the mutex should assume my purpose is to
acquire it and therefore eagerly allocate resources...
Andrei
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]