Re: why creating pointer to reference member is illegal?
On Mar 10, 4:09 am, blargg....@gishpuppy.com (blargg) wrote:
Amazingly, none of the replies answered your question, because your
question looks like a much more common question. They answered the
following question:
int main()
{
int i;
Test t( &i );
int&* p = &t.ref; // why can't I do this?
}
Now that the wrong question is out of the way, perhaps we can now address
your question of why one can't take a pointer to MEMBER (not object) where
the member is a reference. Just as a refresher, this takes a pointer to
member for a NON-reference type:
typedef int T; // why doesn't this work if changed to int&?
struct X { T i; };
void example( X& x )
{
T X::*mptr = &X::i; // get pointer to member
x.*mptr = 123; // now dereference it on an object
}
Why can't we do the same thing when i is of type int&?
For the same reason why you can't have a pointer to a non-member
reference - because it's not an object, meaning that there may be
nothing to point to.
To explain what I mean, let me try to delve into implementation
details. The obvious way to implement a pointer to data member is to
just store the offset from the beginning of containing object. Given
that a reference member may not actually use any storage, it would not
have any offset at all to be used in this case. Of course alternative
schemes are possible, but they would be so much more expensive - and
what is the benefit?
For an example of when a compiler could possibly have a member
reference that doesn't use storage, consider this:
class foo {
foo& self;
foo() : self(*this) {}
};
It seems quite possible for a smart code analyzer to figure out that
self is always bound to *this, and that all references to self are
going to happen where *this is available anyway (since self is
private), thus allowing for direct substitution, and making the
storage redundant. I do not know of any compiler that actually does
that sort of thing today, but I don't see why it would be invalid.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]