c++ - 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
解决方案
在您发布的代码中,&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?
推荐阅读
- javascript - D3 桑基定制
- javascript - 正则表达式 - 如何在仅输入一次后替换字符串中的特定字符?
- sql - sql和and和存储在文件中的图像之间的图像比较
- react-native - 如果向 CodePush 发送不受支持的 React-Native 组件会发生什么?
- selenium - ExtentSparkerReporter 不刷新
- android - 仅对android textview的背景进行动画处理
- c - 与 dup2() 相同的替代方式/方法
- azure-functions - 如果 Web App 或 Function App 没有响应,如何发送警报?
- c++ - 一个变量可以接收多种类型的数据吗?
- macos - Apple 是否已经从 OSX Monterrey 中删除了 OpenGL 支持?