MichaelFox
MichaelFox

Reputation: 33

Does std::vector automatically do deep copies of pointers to arrays from one vector object to another?

If I have two std::vector objects and I attempt to copy one to another using the assignment operator:

v2 = v1;

Will it create a deep copy of the array pointed to by v1 automatically? Or do I have to overload the assignment operator whenever I want to do this, if I am using std::vector in another class that I am writing?

Upvotes: 0

Views: 3835

Answers (2)

sonulohani
sonulohani

Reputation: 1303

You are making a deep copy any time you copy a vector. But, if you have a vector of pointers, you are only getting a copy of the pointers, not the values they are pointing at.

For example:

std::vector<Foo> f;
std::vector<Foo> cp = f; //deep copy. All Foo copied

std::vector<Foo*> f;
std::vector<Foo*> cp = f; //deep copy (of pointers), or shallow copy (of objects).
//All pointers to Foo are copied, but not Foo themselves

Upvotes: 7

Sword Destiny
Sword Destiny

Reputation: 31

C++ vector is auto deep copy. But the vector element is not. So you need to overload operator= of the element if it's a complex structure include pointer.

Upvotes: 2

Related Questions