首页 > 解决方案 > int*&x 的问题

问题描述

我在取消引用指针时遇到问题

int x = 12;
int* y = &x;
int* &a = y;//This does work
int* &b = &x;//This does not work

不包含相同类型的值/相同的值y&x谁能告诉我int*& a实际代表什么。

编辑:1 抱歉,我没有意识到这样一个简单的代码会在c和 in 中产生两个不同的结果c++。在c这一行int*& a = y中简直是一个错误。但是,在 中c++,代码给出了我所显示的错误。

编辑:2

int *&a = y; //compiles in g++ 7.3.0 ubuntu, but not in gcc 7.3.0

int *&b = &x; //it simply throws error in g++ and gcc

标签: c++pointers

解决方案


在您发布的代码中,&x是一个右值,因此如果要捕获对它的引用,则必须使用 const 引用捕获它。

你需要的是int* const& b = &x.

我学到的,今天仍然对我有用的规则是从右到左阅读声明以理解constness。在这种情况下,您会读到类似“ b 是对指向 int 的 const 指针的引用”之类的内容。

引用必须引用变量(即类型的命名实例)。常量引用可以引用临时对象/无名变量。例如

int x = 5; // x is a named instance of an int
int* p = &x;
int*& y = p; // the reference y is referring to the named variable p which is a pointer to an int.
int*& z = &x; // not ok because x is a named variable but "&x" is not, so a reference cannot refer to it.
int* const& w = &x; // ok because w is a const reference, not a reference.

希望有帮助。花一些时间在线阅读有关引用和 const 正确性的信息,这一切都会变得明朗。关于这两个主题,这里有很多很棒的问答。


这是一篇讨论左值和右值的好文章:什么是右值、左值、xvalues、glvalues 和 prvalues?


推荐阅读