Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unordered_map with reference as value

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.

Update

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.

like image 885
developerbmw Avatar asked Jul 13 '14 02:07

developerbmw


1 Answers

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;
}
like image 108
galop1n Avatar answered Sep 29 '22 11:09

galop1n