Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
代码如下:
class A; shared_ptr<A> aPtr(new A()); //do something with aPtr.
如果 new 抛出 bad_alloc 异常,智能点 aPtr 发生了什么?我需要对 aPtr 做一些检查吗?该怎么做?而且我知道 Google C++ 程序规则之一是从不使用异常,但它们如何处理 bad_alloc 之类的异常?感谢您的任何回复。
如果你得到一个bad_alloc你几乎搞砸了。我不确定您希望如何处理此处的分配失败。在这种情况下,不使用异常并不真正适用。
bad_alloc
如果您真的想退出它,您可以在nothrow该语句中添加 a ,它会返回nullptr而不是抛出 a bad_alloc:
nothrow
nullptr
shared_ptr<A> aPtr(new (std::nothrow) A());
有关更多信息,请参阅有关所涉及的设计考虑的问题。另外看到这个问题解释为什么使用std::nothrow是一个坏主意。
std::nothrow