std::string vs. char*

前端 未结 3 512
滥情空心
滥情空心 2021-02-04 07:56

does std::string store data differently than a char* on either stack or heap or is it just derived from char* into a class?

3条回答
  •  醉话见心
    2021-02-04 08:42

    char*

    • Is the size of one pointer for your CPU architecture.
    • May be a value returned from malloc or calloc or new or new[].
      • If so, must be passed to free or delete or delete[] when you're done.
      • If so, the characters are stored on the heap.
    • May result from "decomposition" of a char[ N ] (constant N) array or string literal.
      • Generically, no way to tell if a char* argument points to stack, heap, or global space.
    • Is not a class type. It participates in expressions but has no member functions.
    • Nevertheless implements the RandomAccessIterator interface for use with and such.

    std::string

    • Is the size of several pointers, often three.
    • Constructs itself when created: no need for new or delete.
      • Owns a copy of the string, if the string may be altered.
      • Can copy this string from a char*.
      • By default, internally uses new[] much as you would to obtain a char*.
    • Provides for implicit conversion which makes transparent the construction from a char* or literal.
    • Is a class type. Defines other operators for expressions such as catenation.
      • Defines c_str() which returns a char* for temporary use.
    • Implements std::string::iterator type with begin() and end().
      • string::iterator is flexible: an implementation may make it a range-checked super-safe debugging helper or simply a super-efficient char* at the flip of a switch.

提交回复
热议问题