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.
Nullability - a scoped_ptr or unique_ptr can be null, a value object can never be. Polymorphism - a value object is always exactly its static type, but you can substitute in different derived types for a unique_ptr. The previously-held object is automatically destroyed when you do this.
std::unique_ptr::unique_ptr The object is empty (owns nothing), with value-initialized stored pointer and stored deleter. construct from pointer (3) The object takes ownership of p, initializing its stored pointer to p and value-initializing its stored deleter.
This means that the definition of class template unique_ptr<> includes an overload of operator = that accepts a value of type nullptr_t (such as nullptr ) as its right hand side; the paragraph also specifies that assigning nullptr to a unique_ptr is equivalent to resetting the unique_ptr .
std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With