In article
<ec1fa5b1-dac7-4111-adb2-c847c8af818f@a1g2000hsb.googlegroups.com>,
wasti.redl@gmx.net wrote:
On 17 Sep., 13:28, Andrei Alexandrescu <SeeWebsiteForEm...@erdani.org>
wrote:
I have the intuition that defining a type with a throwing default
constructor has bad style all over it.
Absolutely not. If, like me, you're not a fan of two-stage
construction, constructors must throw whenever they cannot fully
initialize the object, arguments or not. If they acquire any resource
that can fail - memory, a mutex, ... - the constructor can throw.
Take, for example, a C++ wrapper around an OS mutex. When you create
it, there's typically no reason to pass any arguments. Maybe some
configuration, but it will have defaults. If the class then fails to
acquire an OS mutex, what should it do? Sit there in an unusable
state, waiting for someone to call lock() just so it can throw? Or
should it throw immediately?
What would the default constructor _usefully_ do that might lead to an
error requiring a throw? In your example, you could easily refactor
the code to only manipulate the OS mutex through a non-default
constructor, leaving the default constructor to perform simple, safe
initialization. In my opinion, this seems like better style, but
perhaps I'm overlooking something.
object.
to pass any parameters.
[ comp.lang.c++.moderated. First time posters: Do this! ]