chadb
chadb

Reputation: 1168

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

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?

Upvotes: 19

Views: 40657

Answers (1)

Dark Falcon
Dark Falcon

Reputation: 44201

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.

Upvotes: 28

Related Questions