mercredi 20 juin 2018

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 new(std::nothrow) char[sz] was successful?
I have two options.

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


enter image description here

enter image description here

Clearly Method 2 seems to work.

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

Code link - https://ideone.com/EuScCq

Aucun commentaire:

Enregistrer un commentaire