By way of illustrating the differences, study this example.
Note that when using a shallow copy via assignment of one
vector to another, changes to structs pointed to in one
vector will appear in the other vector as well. Both
vectors have pointers to the same structs.
By contrast, when using a deep copy which allocates new
structs and copies the contents from the structs in the
original vector changes to structs in one vector do
not affect the contents of the structs in the other vector.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct S {
int id;
string name;
};
void ListVect(vector<S*>& v)
{
for (size_t n = 0; n < v.size(); ++n)
{
cout << v[n]->id << " " << v[n]->name << endl;
}
}
int main()
{
vector<S*> vsp1;
vector<S*> vsp2;
S *s1 = new S{1, "Name1"};
S *s2 = new S{2, "Name2"};
vsp1.push_back(s1);
vsp1.push_back(s2);
cout << "Shallow copy:\n";
ListVect(vsp1);
vsp2 = vsp1;
ListVect(vsp2);
cout << endl;
vsp1[0]->id = 3;
vsp1[0]->name = "Name3";
ListVect(vsp1);
ListVect(vsp2);
cout << "\nDeep copy:\n";
vsp2.clear();
for (size_t n = 0; n < vsp1.size(); ++n)
{
S *s = new S{ vsp1[n]->id, vsp1[n]->name };
vsp2.push_back(s);
}
ListVect(vsp1);
ListVect(vsp2);
cout << endl;
vsp1[0]->id = 4;
vsp1[0]->name = "Name4";
ListVect(vsp1);
ListVect(vsp2);
std::cout << "Press any key and Enter to end.";
char c;
cin >> c;
}
Output:
Shallow copy:
1 Name1
2 Name2
1 Name1
2 Name2
3 Name3
2 Name2
3 Name3
2 Name2
Deep copy:
3 Name3
2 Name2
3 Name3
2 Name2
4 Name4
2 Name2
3 Name3
2 Name2
Press any key and Enter to end.
- Wayne