Hey so I'm writing a function that will return the correct class if the name is found. In the case that I don't find a class what and how should I return.
std::vector<std::shared_ptr<myClass>> myClasses;
class myClass{
std::string name = "bob";
myClass();
};
std::shared_ptr<myClass> getMyClass(const std::string _name){
for (auto& x : myClasses){
if (x->name == _name){
return x;
}
}
// Else return nullptr???
return std::make_shared<myClass>(nullptr);
}
Before I had tried to return by myClass& but that seems to cause me more problems when trying to return null. I am trying to get it to the point where I can call my getMyClass
function and It will return the class if found and nothing otherwise.
std::shared_ptr
would be a way to return a null-pointer. That seems reasonable enough to me, what is your problem with that?return std::make_shared<myClass>();
? That gives me compiler errors about no matching function for std::construct_atreturn std::shared_ptr<myClass>();
. Or even simplerreturn {};
. Evenreturn nullptr;
should workstd::optional
. Option 2:std::shared_ptr<myClass>{}
. Option 3:throw
an exception (if such is really an exceptional situation).