Just a simple quick question which I couldn\'t find a solid answer to anywhere else. Is the default operator= just a shallow copy of all the class\' members on the right ha
Yes, default operator=
is a shallow copy.
By the way, the actual difference between shallow copy
and deep copy
becomes visible when the class has pointers as member fields. In the absence of pointers, there is no difference (to the best of my knowledge)!
To know the difference between them, see these topics (on stackoverflow itself):
As illustrated by the code snippet below, the = (assignment) operator for STL performs a deep copy.
#include <iostream>
#include <stack>
#include <map>
#include <vector>
using namespace std;
int main(int argc, const char * argv[]) {
/* performs deep copy */
map <int, stack<int> > m;
stack <int> s1;
stack <int> s2;
s1.push(10);
cout<<&s1<<" "<<&(s1.top())<<" "<<s1.top()<<endl; //0x7fff5fbfe478 0x100801200 10
m.insert(make_pair(0, s1));
cout<<&m[0]<<" "<<&(m[0].top())<<" "<<m[0].top()<<endl; //0x100104248 0x100803200 10
m[0].top() = 1;
cout<<&m[0]<<" "<<&(m[0].top())<<" "<<m[0].top()<<endl; //0x100104248 0x100803200 1
s2 = m[0];
cout<<&s2<<" "<<&(s2.top())<<" "<<s2.top()<<endl; //0x7fff5fbfe448 0x100804200 1
s2.top() = 5;
cout<<&s2<<" "<<&(s2.top())<<" "<<s2.top()<<endl; //0x7fff5fbfe448 0x100804200 5
cout<<&m[0]<<" "<<&(m[0].top())<<" "<<m[0].top()<<endl; //0x100104248 0x100803200 1
cout<<endl<<endl;
map <int, stack<int*> > mp;
stack <int*> s1p;
stack <int*> s2p;
s1p.push(new int);
cout<<&s1p<<" "<<&(s1p.top())<<" "<<s1p.top()<<endl; //0x7fff5fbfe360 0x100805200 0x100104290
mp.insert(make_pair(0, s1p));
cout<<&mp[0]<<" "<<&(mp[0].top())<<" "<<mp[0].top()<<endl; //0x1001042e8 0x100806200 0x100104290
mp[0].top() = new int;
cout<<&mp[0]<<" "<<&(mp[0].top())<<" "<<mp[0].top()<<endl; //0x1001042e8 0x100806200 0x100104320
s2p = mp[0];
cout<<&s2p<<" "<<&(s2p.top())<<" "<<s2p.top()<<endl; //0x7fff5fbfe330 0x100807200 0x100104320
s2p.top() = new int;
cout<<&s2p<<" "<<&(s2p.top())<<" "<<s2p.top()<<endl; //0x7fff5fbfe330 0x100807200 0x100104340
cout<<&mp[0]<<" "<<&(mp[0].top())<<" "<<mp[0].top()<<endl; //0x1001042e8 0x100806200 0x100104320
cout<<endl<<endl;
vector<int> v1,v2;
vector<int*> v1p, v2p;
v1.push_back(1);
cout<<&v1<<" "<<&v1[0]<<" "<<v1[0]<<endl; //0x7fff5fbfe290 0x100104350 1
v2 = v1;
cout<<&v2<<" "<<&v2[0]<<" "<<v2[0]<<endl; //0x7fff5fbfe278 0x100104360 1
v2[0] = 10;
cout<<&v2<<" "<<&v2[0]<<" "<<v2[0]<<endl; //0x7fff5fbfe278 0x100104360 10
cout<<&v1<<" "<<&v1[0]<<" "<<v1[0]<<endl; //0x7fff5fbfe290 0x100104350 1
cout<<endl<<endl;
v1p.push_back(new int);
cout<<&v1p<<" "<<&v1p[0]<<" "<<v1p[0]<<endl; //0x7fff5fbfe260 0x100104380 0x100104370
v2p = v1p;
cout<<&v2p<<" "<<&v2p[0]<<" "<<v2p[0]<<endl; //0x7fff5fbfe248 0x100104390 0x100104370
v2p[0] = new int;
cout<<&v2p<<" "<<&v2p[0]<<" "<<v2p[0]<<endl; //0x7fff5fbfe248 0x100104390 0x1001043a0
cout<<&v1p<<" "<<&v1p[0]<<" "<<v1p[0]<<endl; //0x7fff5fbfe260 0x100104380 0x100104370
return 0;
}