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

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

    No, it can't be relied on, but storing read-only string constants in a pool is a pretty easy and effective optimization. It's just a matter of storing an alphabetical list of strings, and then outputting them into the object file at the end. Think of how many "\n" or "" constants are in an average code base.

    If a compiler wanted to get extra fancy, it could re-use suffixes too: "\n" can be represented by pointing to the last character of "Hello\n". But that likely comes with very little benifit for a significant increase in complexity.

    Anyway, I don't believe the standard says anything about where anything is stored really. This is going to be a very implementation-specific thing. If you put two of those declarations in a separate .cpp file, then things will likely change too (unless your compiler does significant linking work.)

提交回复
热议问题