2012-12-14 189 views
0

我正在存儲一個std::mapstd::shared_ptr<V>作爲值。Cast map <K,shared_ptr <V>>來映射<K,shared_ptr <const V>>?

從一個函數中,我想返回一個對這個地圖的引用,但是std::shared_ptr<const V>作爲值類型,那有可能嗎?

這裏是我想達到的目標:

#include <map> 
#include <memory> 

struct A { 
    std::map<int, std::shared_ptr<int>> map; 

    const std::map<int, std::shared_ptr<const int>>& ret1() const { 
     return map; 
    } 
}; 

但是這段代碼不能編譯:

error: invalid initialization of reference of type 
'const std::map<int, std::shared_ptr<const int> >&' 
from expression of type 'const std::map<int, std::shared_ptr<int> >' 

感謝

回答

1

A型T和類型const T相關但最終不同類型。如果您不希望ret1的調用者修改地圖中的值,請返回地圖的副本,或者接受對地圖的引用作爲參數,然後將這些鍵和值複製到該地圖中。

相關問題