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.
std::unique_ptr<T> myptr;doesn't allocate any memory, so you don't need to construct it and passnullptrat all. So you can just create one and return it.nullptris a keyword new in C++11 for better support of null pointers.unique_ptrcan be constructed fromnullptr, even implicitly.unique_ptr? en.cppreference.com/w/cpp/memory/unique_ptra != bas!(a == b), details in this answer.