Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 482
chadb Avatar asked Apr 29 '12 00:04

chadb


People also ask

How does a copy constructor work?

Copy constructors are the member functions of a class that initialize the data members of the class using another object of the same class. It copies the values of the data variables of one object of a class to the data members of another object of the same class.

How is copy constructor invoked?

The copy constructor is invoked when the new object is initialized with the existing object. The object is passed as an argument to the function. It returns the object.

What happens if you use the default copy constructor for vector?

The default copy constructor will copy all members – i.e. call their respective copy constructors. So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.


1 Answers

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.

like image 154
Dark Falcon Avatar answered Oct 06 '22 00:10

Dark Falcon