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");
Answers. Please note that in new STL (Visual Studio 2003 and 2005), the std::string class uses a combined variant of allocating strings. If the length is long then the string is allocated in heap area, but if is short, it is stored in a preallocated area of the class, i.e. in a data member declared as "char s[...]".
They are not stored in the heap until unless we use malloc/calloc. C++ however have many many classes and libraries that abstract the storage away from the developer.
The stack will store the value of the int literal and references of String and Demo objects. The value of any object will be stored in the heap, and all the String literals go in the pool inside the heap: The variables created on the stack are deallocated as soon as the thread completes execution.
Stack space contains specific values that are short-lived whereas Heap space used by Java Runtime to allocate memory to objects and JRE classes. In Java, strings are stored in the heap area.
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.
It depends on the implementation and length of the string.
Most major implementations have short string optimization (SSO), where the string is stored in the string object itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With