2015-04-02 57 views
2

該代碼失敗在Visual Studio 2013來編譯:std :: unordered_map引用作爲值不起作用?

#include <iostream> 
#include <unordered_map> 

class MyClass 
{ 
public: 
    char a; 
}; 

int main() 
{ 
    std::unordered_map<int, MyClass&> MyMap; 
    MyClass obj; 
    obj.a = 'a'; 
    MyMap.emplace(1, obj); 
    std::cout << MyMap[1].a; 
} 

隨着這些錯誤消息:

Error 1 error C2440: 'initializing' : cannot convert from 'int' to 'MyClass &' c:\program files (x86)\microsoft visual studio 12.0\vc\include\tuple 746 

Error 2 error C2439: 'std::pair<const _Kty,_Ty>::second' : member could not be initialized c:\program files (x86)\microsoft visual studio 12.0\vc\include\tuple 746 

當我將其更改爲指針,它編譯罰款。作爲std :: unordered_map中的值類型,引用是否無效?

與boost :: unordered_map相同的代碼可以正常工作。

+0

作爲一個猜測,是因爲你使用的emplace,它直接在構造函數中使用給定的值,但你的類沒有複製構造函數? – 2015-04-02 22:26:23

+1

@Ben如何做_you_複製參考? – sehe 2015-04-02 22:27:20

+0

@sehe,ahhhh,沒關係。我應該仔細閱讀。 – 2015-04-02 22:28:11

回答

3

參考文件不可複製也不可轉讓。它們不支持任何標準庫容器中的值類型。

可以存儲std::reference_wrapper<MyClass>或者,如果你做多的與任何容器幾乎等同MyClass*雖然

0

集裝箱值必須是可複製或移動。顯然,這是不可能的參考。因此,你的程序是非法的。