Is it legal to have an unordered_map with the value type being a reference C++11?
For example std::unordered_map<std::string, MyClass&>
I have managed to get this to compile with VS2013 however I'm not sure whether it's supposed to as it is causing some strange runtime errors. For example vector subscript out of range
is thrown when trying to erase
an element.
Some googling resulted in finding out that you can't have a vector of references but I can't find anything about an unordered_map.
Further experimentation has shown that the vector subscript out of range
was not related to the unordered_map of references as it was a bug in my code.
map
and unordered_map
are fine with references, here a working example :
#include <iostream>
#include <unordered_map>
using UMap = std::unordered_map<int,int&>;
int main() {
int a{1}, b{2}, c{3};
UMap foo { {1,a},{2,b},{3,c} };
// insertion and deletion are fine
foo.insert( { 4, b } );
foo.emplace( 5, d );
foo.erase( 4 );
foo.erase( 5 );
// display b, use find as operator[] need DefaultConstructible
std::cout << foo.find(2)->second << std::endl;
// update b and show that the map really map on it
b = 42;
std::cout << foo.find(2)->second << std::endl;
// copy is fine
UMap bar = foo; // default construct of bar then operator= is fine too
std::cout << bar.find(2)->second << std::endl;
}
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