|
Boost : |
From: Giovanni Piero Deretta (gpderetta_at_[hidden])
Date: 2007-02-13 04:40:29
On 2/13/07, Felipe Magno de Almeida <felipe.m.almeida_at_[hidden]> wrote:
> On 2/12/07, Jeffrey Yasskin <jyasskin_at_[hidden]> wrote:
> > On 2/9/07, Felipe Magno de Almeida <felipe.m.almeida_at_[hidden]> wrote:
> > > On 2/9/07, Mathias Gaunard <mathias.gaunard_at_[hidden]> wrote:
> > > > Felipe Magno de Almeida wrote:
> > > > > Why would it? T* and T& have very different semantics.
> > > >
> > > > An optional T& has closer semantics to T* than a non-optional one.
> > >
> > > Didn't understand what you mean. Could you rephrase?
> >
> > An optional<T&> has nearly the same semantics as a T*. I think the
> > only thing it's missing is pointer arithmetic, and it may be a little
> > more clear that optional<T&> is non-owning (though less clear that
> > it's Assignable). So I'm not sure either why anyone should use
> > optional<T&> instead of T*.
>
> I would say because of the ownership, but you said yourself.
>
I use optional<T&> for optional parameters to functions. It makes the
interface cleaner than having a pointer (no need for the caller to use
the address-of operator), it is more self-documenting and of course it
makes ownership cleaner.
Also, if you have more than one parameters, the syntax to skip an
optional one is cleaner:
foo(optional<A&> = optional<A&>(), optional<B&> = optional<B&>());
...
B x;
foo(none, x);
Instead of:
foo2(A*, B*);
...
B x;
foo2(0, &x);
// ^-- I'm passing an integer or a pointer?
In fact by just looking at the prototype of foo2 you do not even know
if you are allowed to pass a null pointer.
Finally, an assert when dereferencing an empty optional (at least in
debug mode) is much much better than a segmentation fault when
dereferencing a null pointer.
Anyways, I think that enabling operator-> for optional<T&> would be
useful. I was surprised too wen it failed to compile.
gpd
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk