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:
if(!sp){}
if(sp==nullptr){}
#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 ==
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.
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.