gpt4 book ai didi

c++ - C++ 中的引用和字面量

转载 作者:太空狗 更新时间:2023-10-29 20:02:29 25 4
gpt4 key购买 nike

我知道“文字”(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com