Strings in static memory instances count

前端 未结 4 2337
无人及你
无人及你 2021-02-19 09:45

As I know compiletime C-like strings are kept in static memory as only one instance. For instance I got both true on gcc 4.6 running example below. But I wonder is

4条回答
  •  隐瞒了意图╮
    2021-02-19 10:07

    No, this is not always true, nor is it portable.

    Merging identical string literals is an optimization that is performed by the compiler and the linker working together. Recent versions of both GCC and Microsoft's compiler both support it, but only when certain optimization switches are set.

    And it's not just an "on" or "off" feature. Different compilers and different optimization settings will also affect how aggressively this is performed. For example, sometimes string literals are pooled only within the scope of an individual function, other times it happens at the level of the translation unit, and still other times the linker might get involved to do it across multiple translation units.

    This is allowed because the C and C++ standards leave this behavior as implementation-dependent.

提交回复
热议问题