如何检查C++智能指针内存分配是否成功?

How to check if C++ smart pointer memory allocation was successful?

考虑以下智能指针的用法std::unique_ptr:

std::unique_ptr<char> sp(new(std::nothrow) char[sz]);

如何检查 new 是否成功?

我有两个选择:

  1. 方法 1 - 检查布尔值:if(!sp){}
  2. 方法 2 - 与空指针比较:if(sp==nullptr){}

示例 (source)

#include <iostream>
#include <memory>
using namespace std;

int main() {
    constexpr long long sz = 1000000e10;
    
    //raw pointer
    auto ptr = new(std::nothrow) char[sz];
    if(ptr==nullptr)
    {
        cout<<"ptr nullptr"<<endl;
    }
    
    //smart pointer
    std::unique_ptr<char> sp(new(std::nothrow) char[sz]);
    
    if(!sp)
    {
        cout<<"sp nullptr bool"<<endl;
    }
    
    if(sp==nullptr)
    {
        cout<<"sp nullptr =="<<endl;
    }
    return 0;
    
}

输出:

Success #stdin #stdout 0s 4396KB
ptr nullptr
sp nullptr bool
sp nullptr ==

显然方法 1 和方法 2 似乎都有效。

不过,我想从权威来源(C++ 标准、msdn、gcc 文档)中了解到这确实是正确的方法。

本人作为权威人士,可以确认这两种方式确实都是正确的。

开个玩笑:std::unique_ptroperator ==(std::nullptr_t) and operator bool 被重载以执行您对指针的期望,所以是的,两者都是正确的,尽管方法 1 更惯用。