开发者

c++ pointer to a reference

Is it legal to have a pointer of a 开发者_如何学Goreference 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.


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.


That code is legal, but it does not create a pointer to the reference. It creates a pointer to the referent (the reference target).


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?


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜