【问题标题】:Need to check for nullptr when make_shared and make_unique is used?使用 make_shared 和 make_unique 时需要检查 nullptr 吗?
【发布时间】:2019-07-18 08:00:50
【问题描述】:

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

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

如果您真的内存不足,std::make_unique 将通过预期。所以你永远不会从std::make_unique 得到一个空指针。 这是正确的吗?

所以当您执行make_sharedmake_unique 时,无需检查nullptr

【问题讨论】:

  • 稍微整理了你的帖子 :)
  • 请注意,您也可以通过if (p)查看。

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


【解决方案1】:

来自std::make_unique 上的 cppreference(std::make_shared 类似):

例外情况

可能抛出std::bad_allocT 的构造函数抛出的任何异常。如果抛出异常,则此函数无效。

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

【讨论】:

  • “无效果”是说没有留下任何垃圾。当然,如果抛出(或者更确切地说是发出)异常,该函数不会返回
  • 如果内存不足,我们究竟会在“p”中得到什么?
  • @Shih-ChanHuang 没有。当抛出异常时,控制流返回到最近的catch 块处理异常,同时清除堆栈及其所有数据,包括p
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-09
  • 2017-05-19
  • 1970-01-01
  • 2014-12-10
  • 2016-04-03
  • 1970-01-01
  • 2020-08-14
相关资源
最近更新 更多