-1

OK, I know that string is a class in C++. Now if I declare an instance somewhat like string str. Is it an array of characters terminated by \0 character only or something is different from regular array of characters?

  • 1
    Does this answer your question? [Does std::string contain null terminator?](https://stackoverflow.com/questions/11752705/does-stdstring-contain-null-terminator) – GoodDeeds Feb 15 '20 at 14:15
  • You can think of a string *instance* as a small object holding the pieces of information: a pointer to string data, the length of the string, and the capacity of the string (how large data was allocated, can be larger or equal to length). In practice it's more complex due to different optimizations and concerns, but that's the basic idea. And yes, the data is nul-terminated, but only for the sake of interoperability with the code that expects C strings. – user4815162342 Feb 15 '20 at 14:29
  • Does this answer your question? [Difference between string and char\[\] types in C++](https://stackoverflow.com/questions/1287306/difference-between-string-and-char-types-in-c) – walnut Feb 15 '20 at 14:50

2 Answers2

2

On the contract level, it's a class that can give you a null terminated array of characters if you want (methods c_str(), data()).

As of C++11, the array returned by the c_str() and also by data() is guaranteed to correspond to the internal storage of the string. Before, that wasn't required by the standard but happened in practice.

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
  • 2
    The second paragraph is not true, since the `data()` method must be able to provide a pointer into the contiguous character storage. (And [as of C++17](https://en.cppreference.com/w/cpp/string/basic_string/data) it is no longer const.) – user4815162342 Feb 15 '20 at 14:23
1

A char array is simply a static allocation of memory on the stack with a char data type. However, Here str is the object of std::string class which is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type.

Do not use cstring or string.h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type.

See the following links for more help: char* vs std:string vs char[] in C++ & Difference between string and char[] types in C++.

Community
  • 1
  • 1
Pikachu
  • 304
  • 3
  • 14