C++ std::unique_ptr return from function and test for null
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.
Yes it's possible. A default constructed unique_ptr
is what you want:
Constructs a
std::unique_ptr
that owns nothing.
// No data found
return std::unique_ptr<myClass>{};
That is equivalent to the nullptr_t
constructor, so perhaps this is more clear:
// No data found
return nullptr;
Yes, it is possible. A default constructed unique_ptr
or one constructed from nullptr
can be considered null:
std::unique_ptr<MyClass> getData()
{
if (dataExists)
return std::make_unique<MyClass>();
return nullptr;
}
To test for null either compare against nullptr
or take advantage of conversion to bool:
int main()
{
std::unique_ptr<MyClass> returnedData = getData();
if (returnedData)
{
...
}
}