Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to member that is a reference illegal?

Tags:

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?

like image 271
fronsacqc Avatar asked Dec 01 '11 03:12

fronsacqc


People also ask

Can you make a pointer to a reference?

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.

Is reference to a reference allowed?

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.

Do pointers need to be passed by reference?

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.

Is reference to a reference allowed in C++?

@Tony: Yes, indeterminate but valid. A function which accepts an rvalue reference, and modifies it, typically does not specify how the reference is modified.


1 Answers

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.

like image 138
Puppy Avatar answered Sep 18 '22 07:09

Puppy