Search code examples
c++classshared-ptr

Returning object with shared_ptr


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.


Solution

  • 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.