How does std::vector's copy constructor operate?

筅森魡賤 提交于 2020-01-01 08:37:09

问题


How does a std::vector<std::string> initialize its self when the following code is invoked

std::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 during newVector = original, but how are the std::string's brought over inside of the orginal? Are they copies or new std::string's? So is the memory in newVector[0] the same as original[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 of DoStuff (on a non optimized build), but if it t is just filled with pointers to the std::string's in globalVector, might the destructor be called and the memory used in std::string deleted, there for making globalVector[0] filled with garbage std::string's after DoStuff is called?

A nut shell, I am basically asking, when std::vector's copy constructor is called, how are the elements inside copied?


回答1:


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.



来源:https://stackoverflow.com/questions/10368602/how-does-stdvectors-copy-constructor-operate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!