简体   繁体   English

c ++指向引用的指针

[英]c++ pointer to a reference

Is it legal to have a pointer of a reference in C++? 在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. 如果func()已经存在于您无法更改的库中,我可以想到为什么您可能想要这样做的一个原因。

It is not. 它不是。 The address of a reference can be taken, but "pointer to a reference of T" is not a valid type. 可以采用引用的地址,但“指向T的引用的指针”不是有效类型。 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? 关于SO的这篇文章有信息 - 为什么指向参考的指针是非法的?

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. 如果“有一个引用的指针”,你的意思是取一个引用的地址(如你的样本: &ref ),那么它是完全合法的。 Any variable is an identifier, hence & can be applied by § 5.3.1-2 of C++-03. 任何变量是一个标识符,因此&可通过C ++的§5.3.1-2被施加- 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 (eg int &* ), then no, by § 8.3.2-4 (and the note at § 8.3.1-4). 如果“有一个引用的指针”是指一个指向引用的指针的类型(例如int &* ),则不是§8.3.2-4(以及§8.3.1-4中的注释)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM