Reputation: 10343
Is it legal to have a pointer of a reference in C++?
For example:
int &ref = array[idx];
func(&ref);
One reason I can think of why you might want to do this if func() already exists in a library which you can't change.
Upvotes: 9
Views: 6073
Reputation: 77400
If by "have a pointer of a reference" you mean taking the address of a reference (as in your sample: &ref
), then it's perfectly legal. Any variable is an identifier, hence &
can be applied by § 5.3.1-2 of C++-03. Expressions with reference types are lvalues, and thus &
is applicable by the same section.
If by "have a pointer of a reference" you mean a type that's a pointer to a reference (e.g. int &*
), then no, by § 8.3.2-4 (and the note at § 8.3.1-4).
Upvotes: -1
Reputation: 437326
It is not. The address of a reference can be taken, but "pointer to a reference of T" is not a valid type. What you are doing here is taking a pointer to the object itself, since a reference to an object simply creates another name by which you can access that same object.
Upvotes: 12
Reputation: 283614
That code is legal, but it does not create a pointer to the reference. It creates a pointer to the referent (the reference target).
Upvotes: 9
Reputation: 34605
Pointer points to an object and reference is not an object to have pointer to it. Reference is just an alias.
This post on SO has information - Why pointers to a reference is illegal?
Upvotes: 0