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

后端 未结 6 1821
清歌不尽
清歌不尽 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:29

    I would not rely on the behavior, because I am doubtful the C or C++ standards would make explicit this behavior, but it makes sense that the compiler does it. It also makes sense that it exhibits this behavior even in the absence of any optimization specified to the compiler; there is no trade-off in it.

    All string literals in C or C++ (e.g. "string literal") are read-only, and thus constant. When you say:

    char *s = "literal";
    

    You are in a sense downcasting the string to a non-const type. Nevertheless, you can't do away with the read-only attribute of the string: if you try to manipulate it, you'll be caught at run-time rather than at compile-time. (Which is actually a good reason to use const char * when assigning string literals to a variable of yours.)

提交回复
热议问题