Boost logo

Boost :

From: Maximilian Wilson (wilson.max_at_[hidden])
Date: 2004-10-08 23:53:04

> Reference gives a different guarantee than pointers. Ok Could still be cast
> to a pointer but ....
> T& x = my_obj(); // reference *feels* like more obvious semantics than
> pointer.
> x.do_it();
> *Ideally* my_obj always holds something... never empty. That is I guess
> problematic from the implementation viewpoint, as it may cause a large
> number of allocations. However it makes the thing extremely simple to use.
> Dont really want to have to do this all the time:
> if( !my_obj.is_empty()){
> my_obj().do_it();
> }

Actually, reference isn't all that different from a pointer except
that you can use the dot operator (and operator <<, +, -, ==, etc.) on
it without dereferencing first. I think you're looking for "smart
references," but C++ doesn't really do them because you can't overload
the dot operator. I bet you could get something very close to what you
want by defining another class smart_object<T> that inherits from
shared_ptr<T>, but suppresses the -> and = operators and has an
implicit conversion to T&. (Implicit conversions are often a bad idea,
and I don't know if this is an exception, but...) As far as reference
semantics, all you really want is a guarantee that a shared_ptr<T> is
always initialized to a non-null value, so make sure there is no
default constructor and you're in business.

I don't know if I recommend actually *doing* this, though. shared_ptr
should probably be sufficient for giving you reference semantics, and
while it's nice to use operators without dereferencing (*myPtr), it's
probably not worth messing with implicit conversions to achieve it.

> OTOH maybe could do:
> share_object<T> my_empty_obj(leave_empty());
> // then make sure its not empty before going public...

I believe that shared_ptr throws an exception if you try to
dereference it while it's empty. If you are mathematically positive
that a shared_ptr has a value (e.g. no default constructor), you don't
even need to set a catch block (although you still ought to run unit
tests, etc.).

Ubi solitudinem faciunt, pacem appellant. 
They make a desert and call it peace.

Boost list run by bdawes at, gregod at, cpdaniel at, john at