作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我知道“文字”(c 字符串、int 或其他)存储在某个地方(显然在只读数据部分 .rodata 中)也许这不准确...
我想了解为什么这段代码会导致运行时错误:
#include <iostream>
using namespace std;
const int& foo()
{
return 2;
}
const char* bar()
{
return "Hello !";
}
int main() {
cout << foo() << endl; // crash
cout << bar() << endl; // OK
return 0;
}
foo 在文字上返回一个 const 引用 (2) 为什么这会导致崩溃?整数 2 存储在 foo() 的堆栈中吗?
另请参阅:Why are string literals l-value while all other literals are r-value?
最佳答案
我明白为什么这令人困惑,所以我会尝试将其分解。
第一种情况:
const int& foo()
{
return 2;
}
return 语句生成一个临时对象,它是文字2
的拷贝。所以它的地址要么不存在,要么与文字 2
的位置不同(假设文字 2
有一个位置 - 不保证)。
它是返回其引用的临时对象。
第二种情况:
const char* bar()
{
return "Hello !";
}
return 语句生成一个临时对象,它是指针 的拷贝,指向第一个元素 文字字符数组。该指针 包含文字数组的实际地址,并且该地址通过复制 返回给调用方。
总结一下。第二个之所以有效,是因为 return 语句采用文字的地址 的拷贝,而不是文字本身的拷贝。 address 的存储是临时的并不重要,因为 address 在临时保存其值崩溃后仍指向正确的位置。
关于c++ - C++ 中的引用和字面量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40048510/
1.字面常量 (1)字面意思是啥就是啥,看其表示就可以知道其值和类型。 (2)有值无名,一用来初始化变量,与一种字符相关联。 #include <stdio.h>int main()
我是一名优秀的程序员,十分优秀!