Ensure that char pointers always point to the same string literal

前端 未结 4 1181
攒了一身酷
攒了一身酷 2021-01-16 12:18

Given the code

// somewhere in the program
const char* p1 = \"Hello World\";

// somewhere else in the program
const char* p2 = \"Hello World\";
4条回答
  •  猫巷女王i
    2021-01-16 12:54

    As Barry shows in their answer the behavior you want is not guaranteed. You're going to have to pay the cost of string comparisons, but you can at least avoid any memory allocations or writing a comparator by using a std::string_view. A std::string_view is a lightweight view of a string that holds a pointer to the string data and the size of the string and it has a built in operator < that will do a lexicographical comparison. That would change your map to

    std::map
    

提交回复
热议问题