Boost logo

Boost :

From: Mathew Robertson (mathew.robertson_at_[hidden])
Date: 2005-07-11 19:12:19


> > One additional thought occurred to me. How does Boost.Optional handle
> > cases where object construction fails? I'm not sure how many approaches
> > exist to the problem of failed constructors, but I think most
> > programmers agree that constructors should rarely (if ever) be allowed
> > to throw an exception. Would it make sense for Boost.Optional to detect
>
> I dont agree. I think that if an object failed to be constructed, it
> MUST throw...

Even more importantly... Objects can fail to construct, or only partially construct, based on some resource exception.

C++ doesn't provide a guarantee that constructors will never throw. So saying that "...counstructors should rarely..." could be equated to "why bounds check". The fact is that you should be handling failure conditions, even if they are rare.

> > failed constructors and consider those objects uninitialized? Here is a
> > contrived example:
>
> IMO, the "catching exception"-way is better. If someone wants to
> return with an unitialized object, then it must try/catch and return
> an unitialized object then(very ugly, but I cant see a better way)...

Failed constructors cannot be considered unitialized, as objects may get partially constructed. And, justifiably, most programmers dont need to care if an object fails to construct, thus allowing the exception to eventually cause the program to exit.

But if you need to ensure that objects get fully constructed, you need to try/catch.

There is a good write up of this in the book 'More effective C++' by Scott Meyers

Mathew Robertson


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk