Ensure that char pointers always point to the same string literal

前端 未结 4 1160
攒了一身酷
攒了一身酷 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条回答
  •  自闭症患者
    2021-01-16 13:02

    There is no such requirement. [lex.string]/15:

    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.

    Best you can do is assert() or just avoid repeating yourself and stick the thing in a function:

    char const* my_literal() { return "Hello World"; }
    
    char const* p1 = my_literal();
    char const* p2 = my_literal();
    

提交回复
热议问题