-1

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

waas1919
  • 2,365
  • 7
  • 44
  • 76

2 Answers2

4

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

To get the regular pointer to the object, use (p.get()) not p.get. Then, to get a reference to the pointed object, dereference the pointer:

return *(p.get());

As commented on NathanOliver post, your code does not handle the case where no suitable image could be found. So it would be recommended to return a pointer (Image* using p.get()) so that NULL can be returned if no image was found (or you may also return a reference to a local static empty Image, it's an alternative). But that is actuallyanother SO question: Return a "NULL" object if search result not found

Community
  • 1
  • 1
jpo38
  • 20,821
  • 10
  • 70
  • 151