On Thu, Apr 21, 2016 at 3:24 AM, Nicholas Nethercote <n.netherc...@gmail.com
> wrote:

> On Thu, Apr 21, 2016 at 7:38 PM, Nicolas Silva <nical.si...@gmail.com>
> wrote:
> > Fallible construction (even with a way to report failure) is annoying if
> > only because the object's destructor has to account for the possible
> > invalid states. I much prefer having a static creation method that will
> > only instantiate the object in case of success, and mark the constructor
> > protected. Something like:
> >
> > static
> > already_AddRefed<Foo> Foo::Create(SomeParams...) {
> >     // logic that may fail...
> >     if (failed) {
> >          return nullptr;
> >     }
> >     return MakeAndAddRef<Foo>(stuffThatDidNotFail);
> > }
>
> So instead of doing the infallible part in the constructor and the
> fallible part in the Init() function, you're suggesting doing the
> fallible part first and only calling the constructor once it succeeds?
> Interesting. I can see it would work nicely for some heap-allocated
> objects. But I see two possible problems:
>
> - It doesn't appear to work with stack-allocated objects?
>

​I think `mozilla::Maybe<T>` works well, as mentioned elsewhere in the
thread. Here is an example of a non-boxed class whose ctor is infallible
and has a factory method returning a `Maybe` where​
​ `None` indicates failure: ​
https://dxr.mozilla.org/mozilla-central/rev/4feb4dd910a5a2d3061dbdd376a80975206819c6/js/public/UbiNodeDominatorTree.h#207-274

​In general I agree with Nicolas: use patterns that make half-constructed
things impossible and avoid the whole mess.​
_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to