Re: Are throwing default constructors bad style, and if so, why?
Mathias Gaunard wrote:
On 21 sep, 03:47, Andrei Alexandrescu <SeeWebsiteForEm...@erdani.org>
wrote:
For example, IMHO move construction should never, ever throw.
That's fine and all, but that's simply not always possible.
What if my object needs to have its address maintained in some sort of
container? If that container is a std::set, for example, I need to
remove the old address and put a new one. That might throw.
That actually suggests to me that std::set should have a conservative
primitive replace that replaces the value sitting at a given iterator
with a new value, without any node allocation. But that's hard because
in C++ defining swapping and move construction modularly are very difficult.
It could be argued, however, that it's not that likely to throw, so
one might as well abort if an exception occurs to make the operation
nothrow.
Since the "move should not throw" is a restriction it will by necessity
limit the number of correct programs. The question is whether the
benefits of the restriction outweigh that loss.
Heck, if deque's constructor attempts to allocate memory (and
consequently throw), you can't even use the swap trick to ensure you
have completely emptied a deque. So picture the irony: _emptying_ a
deque via the swap trick could _throw_. This is a correctness issue that
I guess simply rules the swap trick out as a method of emptying a
container in C++03.
It's not deque-specific.
All default constructors of containers are not required to be nothrow.
Electronic Arts has asked the standard to change that, however,
showing their own EASTL as an improvement upon the STL.
I'm of the same opinion as them.
Andrei
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]