Boost logo

Boost :

From: Andy Little (andy_at_[hidden])
Date: 2004-10-09 04:51:54


"Maximilian Wilson" <wilson.max_at_[hidden]> wrote in message
news:2ddbda5f04100821532684f2f8_at_mail.gmail.com...
> > 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

The critical difference between a reference and a pointer (in the classical
sense) is that a reference is guaranteed to refer to some object, else the
program is ill-formed. Further a reference cannot be rebound. This makes it
much more closely associated with a particular object, which in this case is
the desired semantics IMO. If I have two functions:

T* get_pointer();
T& get_reference();

There is no need to (nor can you) check the result of the second but it
would be Very Wise to check always that the result of the first is not 0.
(Otherwise presumably it would return a reference). Hey... I know this is
obvious but just trying to put this in context.

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

It Might be useful that the shared_object doesnt feel exactly like a stack
allocated object. Typically == would be used to check that two
shared_objects are in fact referring to the same object, rather than that
the values in objects they refer to are the same. Function call is one way
to provide access.

> I don't know if I recommend actually *doing* this, though. shared_ptr

I don't know either... I'm just *mucking about* with it. Bearing in mind
that the default ctor allocates this is *amusing*:

struct Someclass{
        shared_object<Someclass> x;
};

Causes an infinite recursion. I used the create_empty() ctor to prevent
this in quick tests... which then leads to requirement for a create()
function ala MFC CWnd. Perhaps they hit the same sort of issues.

It seems that neither the tentative shared_object above, nor a shared_ptr
give quite the perfect semantics for a shared object (hence the
proliferation of smart pointers). Perhaps there is a new type lurking here
somewhere... OTOH perhaps I'm trying to invent a perpetual motion
machine...:-)

regards
Andy Little


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