如果 new 抛出 std::bad_alloc 是否会将指针设置为 NULL?
我知道如果失败,执行 new(std::no_throw) 会将指针设置为 NULL。 我还知道,如果失败,普通的 new 会抛出 std::bad_alloc 异常。
如果抛出异常,普通的 new 也会将指针设置为 NULL 吗?或者我应该在 catch()
块中将其设置为 NULL
吗?
I know doing a new(std::no_throw)
will set pointer to NULL
if it failed.
I also know that a normal new
will throw a std::bad_alloc
exception if it failed.
Will the normal new
also set the pointer to NULL
if it throws? Or should I set it to NULL
in the catch()
block?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C++ 中,错误的
new
会抛出异常(除非您使用 std::nothrot),并且指针不会被分配,因此它将是new
之前的内容。已拨打电话。但是,您可能对本文感兴趣 其中讨论了强制
new
在失败时返回 null,正如您在问题中提到的那样。In C++ a bad
new
will throw an exception (unless you use std::nothrow) and the pointer will not be assigned so it'll be whatever it was before thenew
call was made.However, you may be interested in this article which talks about forcing
new
to return null on failure as you mentioned in your question.当抛出异常时,堆栈将被展开(运行本地对象的析构函数),直到
catch
停止异常。没有任何东西会自动将指针设置为 NULL,并且析构函数之一不太可能这样做 - 这将是一个人为的示例。通常,不需要将指针设置为
NULL
。事实上,很多时候你做不到。采取以下代码:这12个字节的分配可能会失败。异常将从 std::string 的构造函数返回。此时,对象
s
不再存在,s
内的指针s._SomeInternalName
也不再存在。因此,如果您尝试在 catch 块中使用s
,编译器将报告错误。如果指针不再存在,显然不能将其设置为 0。When an exception is thrown, the stack is unwound (running destructors of local objects) until a
catch
stops the exception. There's nothing that automatically sets the pointer toNULL
, and it's unilkely that one of the destructors does so - it would be a contrived example that did.Usually, there's no need to set the pointer to
NULL
. In fact, often you can't. Take the following code:It's possible that the allocation of those 12 bytes fails. The exception will return from the constructor of
std::string
. At that point, the objects
no longer exists, nor does the pointers._SomeInternalName
insides
. The compiler will therefor report an error if you try to uses
in the catch block. And if the pointer doesn't exist anymore, you obviously can't set it to 0.