Search code examples
c++c++11new-operatorsmart-pointersunique-ptr

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


Consider the following usage of smart pointer std::unique_ptr:

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

How can I check if the new was successful?

I have two options:

  1. Method 1 - Check for bool value: if(!sp){}
  2. Method 2 - Compare against null pointer: if(sp==nullptr){}

Example (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;
    
}

Output:

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

Clearly both Method 1 and Method 2 seem to work.

I would however like to read from an authoritative source (C++ standard, msdn, gcc documentation) that this indeed is the correct way.


Solution

  • I, as an authoritative source, can confirm that both ways are indeed correct.

    Just kidding: std::unique_ptr's operator ==(std::nullptr_t) and operator bool are overloaded to perform what you'd expect from a pointer, so yes, both are correct, although method 1 is more idiomatic.