This code fails to compile in Visual Studio 2013:
#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;
}
With these error messages:
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
When I change it to pointers, it compiles fine. Are references invalid as value types in std::unordered_map?
The same code works fine with boost::unordered_map.
References aren't copyable nor assignable. They're not supported as value types in any standard library container.
You can store std::reference_wrapper<MyClass> or, almost equivalently MyClass* though
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With