gpt4 book ai didi

c++ - 通过引用捕获异常对象、临时对象、生命周期问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:16 26 4
gpt4 key购买 nike

考虑以下代码:

#include <iostream>
#include <stdexcept>

void foo()
{
throw std::runtime_error("How long do I live?");
}

int main()
{
try
{
foo();
}
catch (std::runtime_error& e)
{
std::cout << e.what() << std::endl;
}
}

为什么我可以通过引用捕获异常,std::runtime_error("How long do I live?") 不是右值吗?

为什么异常对象在 catch block 中仍然存在?

抛出的异常对象到底存放在哪里?他们的生命周期是多少?

最佳答案

在 C++ 标准中,第 15.1.4 段:

The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.3.1. The temporary persists as long as there is a handler being executed for that exception. In particular, if a handler exits by executing a throw; statement, that passes control to another handler for the same exception, so the temporary remains. When the last handler being executed for the exception exits by any means other than throw; the temporary object is destroyed and the implementation may deallocate the memory for the temporary object; any such deallocation is done in an unspecified way. The destruction occurs immediately after the destruction of the object declared in the exception-declaration in the handler.

请注意,在 C++ 标准谈话中,处理程序表示具有正确参数类型的 catch block 。

关于c++ - 通过引用捕获异常对象、临时对象、生命周期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1860064/

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