Is storage for the same content string literals guaranteed to be the same?

前端 未结 4 1748
余生分开走
余生分开走 2021-01-03 19:22

Is the code below safe? It might be tempting to write code akin to this:

#include 

const std::map m = {
    {\"text1\", 1         


        
4条回答
  •  天涯浪人
    2021-01-03 20:17

    Whether or not two string literals with the exact same content are the exact same object, is unspecified, and in my opinion best not relied upon. To quote the standard:

    [lex.string]

    16 Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified.

    If you wish to avoid the overhead of std::string, you can write a simple view type (or use std::string_view in C++17) that is a reference type over a string literal. Use it to do intelligent comparisons instead of relying upon literal identity.

提交回复
热议问题