开发者

value_type for a map having pointers as key

开发者 https://www.devze.com 2023-04-13 08:33 出处:网络
For what I know, C++ defines map<a,b>::value_type as pair<const a,b> What will happen if I use a pointer type as key type in map, i.e., is

For what I know, C++ defines map<a,b>::value_type as pair<const a,b>

What will happen if I use a pointer type as key type in map, i.e., is

std::map<const char*,int>::value_type::first_type = const char*

as I would expect from definition above or

std::map<const char*,int>::value_type::first_type = const char* const

as would be more logical (since otherwise i would be allowed to开发者_开发技巧 change key value from a map iterator)?


Your reasoning is correct, value_type::first would be char const * const.

There is a common source of confusion in thinking that const T when T is a type * is const type *, but that is not so. Unlike macros, typedefs are not text substitution, nor are template arguments. When you do const T, if T is a typedef or template argument, you are adding a const to the type as a whole.

That is the one reason why I like to write my consts at the right of the type, as it causes less confusion: T const *, add an extra const, get T const * const.


If a is const char*, then const a is indeed const char* const.


You are correct in your assessment, but you have to be very careful with this approach for two reasons:

  1. You have to supply a custom comparator predicate that does proper ordering of const char * (e.g., using a variant of strcmp that only returns true if key1 < key2 ). If you do not do this, your strings will be ordered by pointer values, which is almost always not what you want.
  2. You have to consider the lifetime of the keys in your map and how they will be deallocated when the map is destroyed.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号