user3771111
user3771111

Reputation: 61

std::unordered_map with references as values does not work?

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.

Upvotes: 3

Views: 2061

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385385

Container values must be copyable or moveable if you do much of anything with the container. Clearly, that is not possible with references. Therefore, your program is illegal.

Upvotes: 0

sehe
sehe

Reputation: 393809

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

Upvotes: 5

Related Questions