Xjames56X Xjames56X - 1 year ago 74
C++ Question

Does a std::string always require heap memory?

I have a simple question. I want to know whether

allocates memory every time in C++.

In my code, it seams that the constructor will use more memory for construct
than for

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

Answer Source

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 not longer permitted, so two distinct strings will be created.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download