unordered_map with reference as value

只愿长相守 提交于 2019-12-07 03:38:52

问题


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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/24719044/unordered-map-with-reference-as-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!