Types of memory:
http://www.gotw.ca/gotw/009.htm
Storage duration:
https://en.cppreference.com/w/cpp/language/storage_duration
1 2 3 4 5 6
|
int main() {
const char* one = "Hello";
std::string two( "World" );
std::vector<std::string> three{ two };
three[0] += "!!";
}
|
The one, two, and three all have automatic storage duration and are allocated from stack.
The
"Hello"
is a constant string literal that is stored in
const data section.
The two may or may not allocate dynamic memory (free store, heap) for storing a copy of value "World".
The three will allocate dynamic memory for a std::string object (that is initialized with value of 'two').
The
three
is in stack. The
three[0]
is in "heap". The
"World!!"
stored by
three[0]
is in heap too. Is it in block allocated by
three[0]
or within
three[0]
?
@jonnin: the keyword is "optimization". We know that std::string is a class. We know that it has a
char*
member. On most implementations the string object is larger than a pointer, so it has some other data members too. It
can have a small array of char. The pointer could point to that, rather than to dynamically allocated array.
Yes, if all your strings are long, then the array member would not be used at all but the waste of space would be relatively small.
Yes, there will be some extra logic for juggling between member and dynamic.
However, if all strings are small enough to fit into the member array, then no dynamic allocations are needed at all.
Is such optimization worth the effort? The authors of a Standard Library implementation make that call.
1 2
|
// How many allocations?
std::vector<std::string> four( 1'000'000, two );
|
If string has the optimization (and "World" fits in it), then only
one: vector allocates array for million strings.
If not, then vector allocates array for million strings and each string allocates an array for its data. 1'000'001 allocations.