gpt4 book ai didi

c++ - C++ 异常参数存储在内存中的位置?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:53 24 4
gpt4 key购买 nike

我对 C++ 异常有疑问:

#include <iostream>
#include <string>

using namespace std;

void some_function()
{
string str("Hello,World!");
throw(str);
}

int main()
{
try
{
some_function();
}
catch (string& e)
{
cout << e << endl;
e = "Hello, the world!";
cout << e << endl;
}

return 0;
}

在我的电脑上调试:

  1. some_function 中的 str 地址:0x003CF820
  2. int main e 地址:0x003CF738

我有三个问题,

  1. catch参数是string&,为什么我们在main()中得到diff addr?
  2. str 不是临时值吗?为什么我们可以使用临时值引用?
  3. e 在内存中存储在哪里?

有人可以帮助我吗?谢谢。

最佳答案

抛出的对象通常被复制/移动到或直接构造到为它们保留的内存区域——不同于普通的函数调用堆栈和“堆”。因此,some_function() 中的本地 str 对象的地址不能期望与 main() 。该模型允许抛出对象的生命周期与在它们被捕获之前发生的堆栈展开分离。 (这也意味着它可能是可能的——如果你关心的话,你会想检查你的实现文档——抛出异常,即使剩余的堆栈和/或堆不足以存储抛出的值,尽管许多异常对象使用进一步的动态存储 - 例如,对于文本长于任何内部短字符串优化缓冲区的 std::string 对象)。

参见 15.1/4:

The memory for the exception object is allocated in an unspecified way, except as noted in 3.7.4.1.

在 3.7.4.1 中:

[ Note: In particular, a global allocation function is not called to allocate storage for objects with static storage duration (3.7.1), for objects or references with thread storage duration (3.7.2), for objects of type std::type_info (5.2.8), or for an exception object (15.1). —end note ]

关于c++ - C++ 异常参数存储在内存中的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20966681/

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