Boost logo

Boost Users :

From: Noah Roberts (roberts.noah_at_[hidden])
Date: 2008-05-21 12:08:31


John Femiani wrote:
>
>
> Max wrote:
>>>> To make it clearer, I'm finding something like this:
>>>> class Foo
>>>> {
>>>> int & i_;
>>>> Foo& operator=(const Foo& rhs)
>>>> {
>>>> if(&rhs == this) return *this;
>>>> i_ = rhs.i_;
>>>> return *this;
>>>> }
>>>> }
>>>>
>>>> this is not accepted by my VC9 compiler.
>>>>
>>> It isn't? I don't see a problem (other than that it may not
>> be what you
>>> intend),
>> Oops, It's indeed not my intention. What I wanted is to bind
>> i_ to rhs.i_;
>>
>
>
> Hi Max,
> First, the C++ standard does not allow a reference to change which
> object it refers to after it has been initialized. Second, I'm just
> curious, why do you want to do this? Why don't you use a pointer? Or
> perhaps wrap a pointer in a class with a typcast operator that produces
> a reference, if you need it to have the same syntax?

Just my two cents, but I would definitely go with the wrapper option or
use a shared_ptr. The other option requires that you track which of the
objects will own the object pointed to and will delete it. Usually you
want this to be the last one anyway so a shared_ptr is very appropriate
here.

Doing this tracking by hand can be a lot of work and there's room in
there for a lot of problems. The amount of care needed in making sure
that everyone knows the details about how this class works often exceeds
the care you think is necessary. I've seen some pretty serious bugs
come out of classes that 'sometimes' shared a pointer with other
instances of the same class.

This is a perfect time for a shared_ptr or other wrapper object to
encapsulate all that crap.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net