Ensure that char pointers always point to the same string literal

前端 未结 4 1162
攒了一身酷
攒了一身酷 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:08

    There is no requirement that two string literals with the same text are the same object. So the two mentions of ”Hello world” may or may not refer to a single string in memory. That means that

    const char* p1 = "Hello World";
    const char* p2 = "Hello World";
    

    Does not necessarily make p1 equal to p2. To do that, you have to set one of them equal to the other:

    const char* p2 = p1;
    

    But either one of those pointers can be modified, and the other pointer won’t track that change. To make sure that such changes can’t be done, make the pointers const:

    const char* const p1 = "Hello World";
    const char* const p2 = p1;
    

    Or, if p1 needs to be modifiable, make p2 a reference:

    const char* p1 = "Hello World";
    const char*& p2 = p1;
    

    Now p2 will point at whatever p1 points at.

提交回复
热议问题