Does a std::string always require heap memory?

Oscar picture Oscar · Oct 6, 2016 · Viewed 6.9k times · Source

I have a simple question. I want to know whether std::string allocates memory every time in C++.

In my code, it seems that the constructor will use more memory to construct tst_first_string than for tst_second_string:

 char* first_string = new char[5];
 strcpy(first_string, "test");
 std::string tst_first_string(first_string);
 std::string tst_second_string("test");

Answer

Bathsheba picture Bathsheba · Oct 6, 2016

Both tst_first_string and tst_second_string will be constructed using the constructor to const char*. Since the number of characters before the nul-terminator is the same in both cases, you'd imagine that the construction will be exactly identical. That said the C++ standard is intentionally vague as to what must happen with regards to memory management so you will not know with absolute certainty.

Note also that many std::string implementations exploit a short string optimisation technique for small strings which causes the entire object to be written to memory with automatic storage duration. In your case, dynamic memory may not be used at all.

What we do know for certain is that from C++11 onwards, copy on write semantics for std::string is no longer permitted, so two distinct strings will be created.