For example, there is a function that finds an object and returns shared_ptr if object is found, and must indicate somehow that no object was found.
std::vector<std::shared_ptr> Storage::objects;
std::shared_ptr<Object> Storage::findObject()
{
if (objects.find)
{
return objects[x];
}
else
{
return nullptr;
}
}
std::shared_ptr<Object> obj = Storage::findObject();
if (obj)
{
print("found");
}
else
{
print("not found");
}
Is it correct to return shared_ptr implicitly initialized with nullptr like in upper example? It will work, but can be it done this way? Or should I return shared_ptr default constructed instead?
What in case it would be weak_ptr? What is proper way to check that empty weak_ptr has been returned? by weak_ptr::expired function or are there other ways? If checking by weak_ptr::expired is the only way then how can I distinguish that function returned empty pointer, or object was just deleted(multi-thread environment)?
optional<T>
seems to be exactly what you want (this seems to be coming into the standard in C++17). If you don't want the overhead, then you basically just have to document that anullptr
is in fact an absence of value and not a mistake.