Let us say I have:
// This is all valid in C++11.
struct Foo {
int i = 42;
int& j = i;
};
// Let's take a pointer to the member "j".
auto b = &Foo::j; // Compiler is not happy here
// Note that if I tried to get a pointer to member "i", it would work, as expected.
Foo f;
std::cout << f.*b; // Try using the pointer to member
The compiler complains that I cannot take the address of the member because it is a reference. To be precise:
Semantic Issue: Cannot form a pointer-to-member to member 'j' of reference type 'int &'
I know doing this seems pointless, but I am only wondering why it cannot be done.
Why is this impossible?
No, you can't make a pointer to a reference. If you use the address-of operator & on it you get the address of the object you're referencing, not the reference itself.
What's going on? A reference is an alias to the object itself. So when you try to make a reference to a reference, the reference passes it on to the object itself so you end up with just another reference to the object.
You would want to pass a pointer by reference if you have a need to modify the pointer rather than the object that the pointer is pointing to. This is similar to why double pointers are used; using a reference to a pointer is slightly safer than using pointers.
@Tony: Yes, indeterminate but valid. A function which accepts an rvalue reference, and modifies it, typically does not specify how the reference is modified.
It cannot be done because you cannot take a pointer to a reference- period.
If you could take a member pointer to a reference, this would be inconsistent with the behaviour of references on the stack. The attitude of C++ is that references do not exist. As such, you cannot form a pointer to them- ever.
For example, &f::a
would have to be different to &f::b
. And by de-referencing &f::b
, you would effectively be achieving a pointer to a reference, which is not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With