首页 > 解决方案 > Need to check for nullptr when make_shared and make_unique is used?

问题描述

If I am creating a pointer using make_shared or make_unique do I ever have to check whether it is nullptr or not, like:

std::unique_ptr<class> p = std::make_unique<class>();
if (p == nullptr)
{
    ....
    ....
}

If you’re really running out of memory, std::make_unique will through an expection. So you will never get a null pointer from std::make_unique. Is this correct ?

So there's no need to check for nullptr when you do make_shared and make_unique?

标签: c++c++11c++14c++17

解决方案


从 cppreference 开始std::make_unique(类似于std::make_shared):

例外

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

“这个函数没有效果”具体意味着它不返回任何东西,因为异常处理机制启动了。所以是的,你的假设是正确的。错误处理std::make_unique是由异常完成的,返回值是 never nullptr


推荐阅读