Boost logo

Boost :

From: Felipe Magno de Almeida (felipe.m.almeida_at_[hidden])
Date: 2005-07-11 04:16:02


On 7/10/05, Jost, Andrew <Andrew_Jost_at_[hidden]> wrote:
> 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...

> 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)...

>// -- begin
>class construct_status { /* TBD */ };
>
>class foo : public construct_status {
> int *i;
>public:
> foo() throw() : i(new(nothrow) int) {
> if( !i ) {
> this->construct_status::set_bad();
> } else {
> this->construct_status::set_good();
> }
> }
>};

>boost::optional<foo> x = foo();
>if( !x ) {
> // end up here if the foo constructor called
>construct_status::set_bad
>}
>// -- end

I dont think this code will work as expected.
The foo will be constructed before optional<foo> starts, so
boost::optional will never get a chance to catch the exception,
neither starts to be constructed.
In this code the if will never be reached.
I dont even think there's a way to do what you want, because the
object wont be constructed inside boost::optional.

>
> It seems that if Boost.Optional users must always test for
> initialization anyway, we could add a valid object check for free. I
> would be interested to hear what others think about this.

But IMO, an exception means that something really wrong happened, and
as so, the code that probably knows how to handle this is way up to
where the exception happened. And after all, that's why exceptions
wind up automatically.

>
> -Andy
>
> _______________________________________________
> Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
>

-- 
   Felipe Magno de Almeida
Developer from synergy and Computer Science student from State
University of Campinas(UNICAMP).
Unicamp: http://www.ic.unicamp.br
Synergy: http://www.synergy.com.br
"There is no dark side of the moon really. Matter of fact it's all dark."

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