简体   繁体   中英

unordered_map with referenced key

I have something wrong with the new C++ unordered_map: I would like to use the operator[] with a const key, but I get rejected.

I cannot give the whole code, but I can simplify my problem like this:

#include <unordered_map>

class A {
    public:
        A();
};

class B {
    public:
        B();
};

int main(int argc, char **argv) {
    std::unordered_map<A &, B> myMap;
    A a;
    const A &ar = a;
    B b;
    myMap[ar] = b;
}

The output of the compiler is a bit long, but ends with:

/usr/include/c++/4.6/bits/hashtable_policy.h:537:5: note:   no known conversion for argument 1 from ‘const A’ to ‘A&’

I use a const A & because, in my code, some method give it to me as is. And, by the way, the key should be const. I have tried a std::unordered_map<const A &, B> myMap; instead, but it does not work either.

I use gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5), with the -std=c++0x flag.

Could you please tell me why this is forbidden? I must say I do not understand the reason.

Many thanks (and please excuse me if the question is stupid...).

The reason is that operator[] is specified as follows (note that the same holds for just std::map ):

Value& operator[](Key const& k);

In your case, Key is A& , so this expands to:

B& operator[](A& const& k);

And since references-to-references are invalid and the top-level reference is dropped when created through typedefs or template parameters, you get just:

B& operator[](A&);

Which can't handle an A const& argument.

In general, I'd advise against using a mutable reference as the key, since mutable keys are a good source for errors.

Using a reference as a key is a Bad Idea: It is bound to cause problems because the life-time of the map and the keys aren't aligned. The key type of your map of references is T& (well, there is a const added at the end but it would be illegal). Trying to bind a T const& to a T& doesn't work. Hence, you can't use T const& to look-up in a map using T& as a key.

There are other things which won't work. You should not try to use a map with a key of T& (or T* for that matter): use values as keys!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM