How does std::vector's copy constructor operate?
std::vector
and most other standard library containers store elements by value. The elements are copied on insertion or when the container is copied. std::string
also maintains its own copy of the data, as far as your usage of it is concerned.
chadb
Updated on January 24, 2020Comments
-
chadb over 4 years
How does a
std::vector<std::string>
initialize its self when the following code is invokedstd::vector<std::string> original; std::vector<std::string> newVector = original;
It would seem as if the copy constructor would be invoked on
std::vector<std::string> new
duringnewVector = original
, but how are thestd::string
's brought over inside of theorginal
? Are they copies or newstd::string
's? So is the memory innewVector[0]
the same asoriginal[0]
.The reason I ask is say I do the following
#include <vector> #include <string> using namespace std; vector<string> globalVector; void Initialize() { globalVector.push_back("One"); globalVector.push_back("Two"); } void DoStuff() { vector<string> t = globalVector; } int main(void) { Initialize(); DoStuff(); }
t
will fall out of scope ofDoStuff
(on a non optimized build), but if itt
is just filled with pointers to thestd::string
's inglobalVector
, might the destructor be called and the memory used instd::string
deleted, there for makingglobalVector[0]
filled with garbagestd::string
's afterDoStuff
is called?A nut shell, I am basically asking, when
std::vector
's copy constructor is called, how are the elements inside copied? -
thb about 12 years@BenjaminLindley: You are right, as far as the container's user is concerned. However, as you most likely know, Stroustrup reminds us that some containers, like
std::string
, may copy data lazily, meaning that the actual copy action might not internally be done until one of the strings (the original or the copy) is used in a manner that requires it to have been done. At any rate, I think that the answerer is technically right to say most in this instance, especially in the manner in which he has qualified his usage. -
Potatoswatter about 12 years@thb
std::string
is only sort-of a container, it is restricted to "char-like types" (i.e. it cannot store other containers), and copy-on-write is deprecated now that multithreading is prevalent. -
thb about 12 years@Potatoswatter: I did not know and had not thought of your multithreading point. Of course you are also right about the "sort-of a container." The correction is accepted with thanks.
-
chadb about 12 yearsSo just to be clear on terminology,
newVector[0] is not the same memory as original[0]
and it the copy constructor is called for the new string? -
Nicol Bolas about 12 years@chadb: Yes, they are independent containers containing independent elements. That just so happen to have the semantically identical contents.