How to return a reference to an object that is in a vector of smart pointers

advertisements

I have a vector of smart pointers to an Image class, like this:

class Controller
{
    //...
    typedef std::vector<std::shared_ptr<Image>> ImageVector;
    ImageVector mImageVector;
}

And I have method that must return a reference to the Image, like this:

Image& Controller::getImage(const std::string name)
{
    for (auto& image : mImageVector)
    {
        std::shared_ptr<Image> p = image;
        if(p->getName() == name) //find the correct pointer to image in the vector
            return p.get; // returns a reference to a image <---ERROR!! What should be here?
    }
}

How can I return a reference to an object, that it is inside a vector of shared_ptr to those objects?

Basically my idea is to make a method that search the vector that has the same string (in the object) as the method parameter. If find, then returns a reference to that object (not to the shared_ptr, but to the object itself).


In

for (auto& image : mImageVector)

image is a reference to the std::shared_ptr in mImageVector. To return a reference to the Image just dereference it.

Image& Controller::getImage(const std::string name)
{
    for (auto& image : mImageVector)
    {
        if(image->getName() == name) //find the correct pointer to image in the vector
            return *image; //return the Image
    }
}

If you ever have to deal with an element not being present in the list then you can return a shared pointer/pointer instead of a reference and set that pointer to null if the item does not exist.