C/C++: Optimization of pointers to string constants

后端 未结 6 1787
清歌不尽
清歌不尽 2020-11-27 08:09

Have a look at this code:

#include 
using namespace std;

int main()
{
    const char* str0 = \"Watchmen\";
    const char* str1 = \"Watchmen         


        
6条回答
  •  独厮守ぢ
    2020-11-27 08:34

    You surely should not rely on that behavior, but most compilers will do this. Any literal value ("Hello", 42, etc.) will be stored once, and any pointers to it will naturally resolve to that single reference.

    If you find that you need to rely on that, then be safe and recode as follows:

    char *watchmen = "Watchmen";
    char *foo = watchmen;
    char *bar = watchmen;
    

提交回复
热议问题