gpt4 book ai didi

c++ - 当构造函数抛出异常时删除运算符段错误

转载 作者:太空宇宙 更新时间:2023-11-04 15:22:08 25 4
gpt4 key购买 nike

最好从代码开始,以了解这一点

#include "Hello1.h"
#include "Hello2.h"

int main(int argc, char ** argv)
{
// Hello1 and Hello2 are derevied classes of Hello
// And there constructor throws an exception
Hello * h;

try
{
if (argv[1][0]=='1')
h = new Hello1;
else
h = new Hello2;
}
catch (std::exception ex) { /*print error*/ }

delete h;
}

如果 Hello1Hello2 抛出异常,它是 segfault。但是如果我添加

Hello h = NULL;

有效!!!

Hello 是一个带有抛出异常的构造函数的类

我能想到的就是构造函数中的异常从内存中删除对象!为什么在哪里谁...解释!请。

最佳答案

However If I add Hello h = NULL; it works!!! Why where who...Explain! Please.

那是因为当指针为null 时,operator delete 什么都不做。它应该什么也不做,这是标准行为。 C++11 标准第 3.7.4.2 段规定:

[...] The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. [...]

另一方面,如果它不是nulloperator delete 将尝试删除hello 指向的对象,并且由于指针未初始化(因为构造抛出并且控制在分配给 hello 之前转移到异常处理程序),您将得到未定义的行为

根据第 5.3.5/2 段:

[...] In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined. [...]

关于c++ - 当构造函数抛出异常时删除运算符段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16334231/

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