1

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.

5
  • 2
    Returning a default constructed std::shared_ptr would be a way to return a null-pointer. That seems reasonable enough to me, what is your problem with that? Commented Nov 30, 2022 at 21:49
  • @UnholySheep What like return std::make_shared<myClass>(); ? That gives me compiler errors about no matching function for std::construct_at Commented Nov 30, 2022 at 21:55
  • 2
    No, just return std::shared_ptr<myClass>();. Or even simpler return {};. Even return nullptr; should work Commented Nov 30, 2022 at 21:56
  • @UnholySheep Wow i feel stupid, that's really helped, thanks; Commented Nov 30, 2022 at 22:01
  • 2
    Option 1: std::optional. Option 2: std::shared_ptr<myClass>{}. Option 3: throw an exception (if such is really an exceptional situation).
    – Eljay
    Commented Nov 30, 2022 at 22:06

1 Answer 1

2

Yes, it is okay for a shared_ptr<T> to be null.

I think the most idiomatic way to return one would be

return {};

from within a function that returns a shared pointer to some type. Returning curly braces like this means to return a "default constructed" object. In this case it will be a shared pointer with nullptr as its raw pointer member.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.