|
Boost Users : |
From: John Femiani (JOHN.FEMIANI_at_[hidden])
Date: 2008-05-21 06:16:03
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?
Something like this:
template<class T>
class assignable_ref{
private:
T* _pointer;
public:
explicit assignable_ref(T& value)
:_pointer(&value)
{}
operator T&() const {
return *_pointer;
}
assignable_ref& operator=(T& rhs) {
_pointer = &rhs;
return *this;
}
assignable_ref& operator=(assignable_ref<T> const & rhs) {
_pointer = rhs._pointer;
return *this;
}
};
class Foo
{
private:
assignable_ref<int> i_;
public:
Foo(int& value) : i_(value){};
Foo& operator=(const Foo& rhs)
{
if(&rhs == this) return *this;
i_ = rhs.i_;
return *this;
}
};
-- John
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