使用make_shared和make_unique时是否需要检查nullptr?

jac*_*row 8 c++ c++11 c++14 c++17

如果我使用make_shared或创建指针,make_unique则是否必须检查它是否为指针nullptr,例如:

std::unique_ptr<class> p = std::make_unique<class>();
if (p == nullptr)
{
    ....
    ....
}
Run Code Online (Sandbox Code Playgroud)

如果您真的用完了内存,请std::make_unique按预期进行。因此,您永远不会从获得空指针std::make_unique。它是否正确 ?

因此nullptr,您无需检查何时make_sharedmake_unique

lub*_*bgr 8

从cppreference开始std::make_unique(与相似std::make_shared):

例外情况

可能会引发std::bad_alloc或的构造函数引发任何异常T。如果引发异常,则此功能无效。

“此功能无效”特别意味着它不会返回任何内容,因为会启动异常处理机制。因此,是的,您的假设是正确的。错误处理std::make_unique是由异常完成的,返回值从不nullptr