2015-12-21 138 views
-1

我有智能指針的vectorImageclass的載體裏面,像這樣:如何參考返回一個對象,它是智能指針

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

我有方法必須返回一個參考到Image,就像這樣:

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? 
    } 
} 

我怎麼能返回引用一個對象,它的shared_ptr對這些對象的一個​​向量裏面?

基本上我的主意是使搜索具有相同的字符串(在對象)的矢量作爲該方法的參數的方法。如果找到,則返回對該對象的引用(不是對shared_ptr,而是對象本身)。

+0

做到像你,如果shared_ptr的是不是矢量的內部。 – juanchopanza

+0

因爲你需要一個可變的空圖像,如果圖像無法找到 - 不行! –

回答

3

for (auto& image : mImageVector) 

imagemImageVector到的std :: shared_ptr的一個參考。要返回對Image的引用,請將其解除引用。

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 
    } 
} 

如果你有對付不存在於列表中的元素,那麼你可以返回一個共享指針/指針,而不是一個參考,並設置指針,如果該項目不存在爲空。

+0

如果沒有找到合適的圖像? – juanchopanza

2

爲了拿到常規指針對象,使用(p.get())p.get。然後,才能到尖對象的引用,取消引用指針:

return *(p.get()); 

上NathanOliver後評論,你的代碼不處理在沒有合適的圖像可能被發現的情況下。因此,這將被推薦到返回(使用p.get()Image*)指針,以便NULL可以返回,如果沒有圖像發現(或者你也可以返回參照當地staticImage,這是一個二選一)。但是,這是actuallyanother SO問題:Return a "NULL" object if search result not found