← Back to Question List
C++ Code Walkthrough #53
Shallow Copy Shares the Buffer
📄 Code
Read carefully — what does this print?1#include <iostream>2using namespace std;34class Shallow {5public:6 int* value;7 Shallow(int v) { value = new int(v); }8 // no copy constructor: the compiler copies the pointer itself9};1011class Deep {12public:13 int* value;14 Deep(int v) { value = new int(v); }15 Deep(const Deep& other) { value = new int(*other.value); }16};1718int main() {19 Shallow s1(5);20 Shallow s2 = s1;21 *s2.value = 9;22 cout << *s1.value << " " << *s2.value << endl;2324 Deep d1(5);25 Deep d2 = d1;26 *d2.value = 9;27 cout << *d1.value << " " << *d2.value << endl;2829 cout << (s1.value == s2.value) << " " << (d1.value == d2.value) << endl;30 return 0;31}