fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. struct S { S(int val = 0) : i(val) {} int i; };
  5.  
  6. struct T
  7. {
  8. T(int Sp = 0) { c = std::shared_ptr<S>(new S(Sp)); }
  9.  
  10. // Copy constructor; 'make_shared' is used instead of 'new' to construct a new object
  11. T(const T& rhs) : c(std::make_shared<S>(*rhs.c)) { }
  12.  
  13. // Assignment operator
  14. T& operator= (T &rhs) {
  15. std::swap(this->c, rhs.c);
  16. return *this;
  17. }
  18.  
  19. std::shared_ptr<S> c;
  20.  
  21. };
  22.  
  23. int main()
  24. {
  25. T objectA(1);
  26.  
  27. // Copy constructor; no resources are shared!
  28. T objectB = objectA;
  29.  
  30. std::cout << std::hex << objectA.c.get() << std::endl;
  31. std::cout << objectB.c.get() << std::endl;
  32. }
  33.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
0x88eca10
0x88eca44