How does the copy constructor std :: vector work?

How std::vector<std::string> initializes itself when the following code is called

 std::vector<std::string> original; std::vector<std::string> newVector = original; 

It would seem that if the copy constructor is called on std::vector<std::string> new during newVector = original , but how is std::string transferred inside orginal ? Are they copies or new std::string ? Thus, the memory in newVector[0] same as original[0] .

I ask you to say that 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 leave the DoStuff (in a non-optimized assembly), but if it is just filled with pointers to std::string in globalVector , the destructor can be called and the memory used in std::string is deleted to create globalVector[0] , garbage-filled std::string after calling DoStuff ?

The shell core, I basically ask when the std::vector copy constructor is called, how are the elements inside copied?

+6
source share
1 answer

std::vector and most other standard library containers store items by value. Elements are copied when pasting or when copying a container. std::string also saves its own copy of the data regarding your use.

+12
source

Source: https://habr.com/ru/post/914432/


All Articles