std vector C++ -- deep or shallow copy

kiriloff picture kiriloff · Jul 5, 2012 · Viewed 77.6k times · Source

I wonder whether copying a vector I am copying the vector with its values (whereas this is not working with array, and deep copy need a loop or memcpy).

Could you hint to an explanation?

Regards

Answer

Andrew picture Andrew · Jul 5, 2012

You are making a deep copy any time you copy a vector. But if your vector is a vector of pointers you are getting the copy of pointers, not the values are pointed to

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