My question is simple. When I use STL containers, do they copy the value I store there (by using copy constructor) or not? What if I give them array of characters (char *) instead of string instance? How do they behave? Is guaranteed that information will be stored in heap instead of system stack?
Thanks for answers.
Values in STL containers are stored by-value. If you have a vector like this:
The vector will make a copy of the object you’re pushing in. Also in the case of a vector, it may make new copies later when it has to reallocate the underlying memory, so keep that in mind.
The same thing is true when you have a vector of pointers, like
vector<char*>— but the difference here is that the value that is copies is the pointer, not the string it points to. So if you have:…the vector will get a copy of the pointer. The pointer it gets will have the same value (0x1234), and since you
deleted that pointer after pushing in the pointer, your vector contains a wild pointer and your code will eventually crash (sooner than later, hopefully).Which, by the way, could have been avoided if instead of using char*s you used strings: