C++ std::unique_ptr return from function and test for null

Mendes picture Mendes · May 18, 2015 · Viewed 66.4k times · Source

I have a function that needs to return a pointer to an object of class myClass. For this purpose I´m using std::unique_ptr.

If the function succeeds, it shall return a pointer to a object with data. If it fails, it should return null.

This is my code skeleton:

std::unique_ptr<myClass> getData()
{
   if (dataExists)
      ... create a new myClass object, populate and return it ...

   // No data found
   return std::unique_ptr<myClass> (null); // <--- Possible?
}

on main:

main()
{
   std::unique_ptr<myClass> returnedData;

   returnedData = getData();

   if (returnedData != null)  // <-- How to test for null?
   {
      cout << "No data returned." << endl;
      return 0;
   }

   // Process data
}

So here goes my questions:

a) Is that (returning an object or null) possible to be done using std::unique_ptr?

b) If possible, how to implement is?

c) If not possible, what are there alternatives?

Thanks for helping.

Answer

R Sahu picture R Sahu · May 18, 2015

Either of the following should work:

return std::unique_ptr<myClass>{};
return std::unique_ptr<myClass>(nullptr);

To test whether the returned object points to a valid object or not, simply use:

if ( returnedData )
{
   // ...
}

See http://en.cppreference.com/w/cpp/memory/unique_ptr/operator_bool.