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.