Strings in static memory instances count

前端 未结 4 2340
无人及你
无人及你 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 09:49

    But I wonder is it always true

    No, at least the C standard says something like "whether two identical string literals are stored in the same array is implementation-defined".

    0 讨论(0)
  • 2021-02-19 09:59

    You're comparing two different string literals, which happen to have the same value. According to the C++ standard, it is implementation defined whether identical string literals occupy the same memory or not (which means that the implementation must document what it does); according to the C standard, it is unspecified. (I presume that the C++ standard would allow the implementation to document something along the lines of "string literals of identical content share the same instance if they are in the same translation unit, and do not share the same instance otherwise.)

    If your goal is to be able to just compare pointers, the usual solution is to use a function (static if it is a class member) which returns the string literal:

    char const*
    value()
    {
        return "Hello";
    }
    
    bool
    isHello( char const* str )
    {
        return str == valule;
    }
    

    and then ensure that all instances of the string are obtained by calling value().

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-19 10:13

    No, it's implementation dependent for both C and C++.

    C11 §6.4.5/7 String literals

    It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

    C++11 §2.14.5/12 String literals

    Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined.

    0 讨论(0)
提交回复
热议问题