fork download
  1. #include <memory>
  2. #include <iostream>
  3.  
  4. /* copyable unique_ptr
  5.  * https://t...content-available-to-author-only...s.com/2015/06/27/cs-rule-of-zero/ */
  6.  
  7. //self-contained version for C++11
  8. template <class T> class copying_unique_ptr : public std::unique_ptr<T> {
  9. public:
  10. copying_unique_ptr(std::unique_ptr<T> &&t)
  11. : std::unique_ptr<T>(std::forward(t)){};
  12. copying_unique_ptr(T *in) : std::unique_ptr<T>(in) {}
  13.  
  14. copying_unique_ptr(copying_unique_ptr<T> &&other) = default;
  15. copying_unique_ptr &operator=(copying_unique_ptr &&other) = default;
  16.  
  17. copying_unique_ptr(const copying_unique_ptr<T> &other)
  18. : copying_unique_ptr(new T(*other)) {}
  19.  
  20. copying_unique_ptr &operator=(const copying_unique_ptr &other) {
  21. std::swap(*this, copying_unique_ptr(other));
  22. return *this;
  23. }
  24. };
  25.  
  26.  
  27. struct DestructorInt {
  28. int i;
  29. ~DestructorInt() {
  30. std::cout << "Destructor here; i = " << i << std::endl;
  31. }
  32. };
  33.  
  34. int main() {
  35. using namespace std;
  36. std::unique_ptr<int> up(new int(3));
  37. cout << *up << endl;
  38.  
  39. copying_unique_ptr<int> cp(new int(3));
  40. cout << *cp << endl;
  41. // copy_ptr<int> cp; //(make_unique<int>(3));
  42. // IntCopyPtr icp(make_unique<int>(3));
  43.  
  44. auto cp2 = cp;
  45. cout << *cp2 << " <- copy / orig -> " << *cp << endl;
  46.  
  47. *cp2 = 5; *cp = 2;
  48. cout << *cp2 << " <- copy / orig -> " << *cp << endl;
  49.  
  50.  
  51. copying_unique_ptr<DestructorInt> dest1(new DestructorInt);
  52. auto dest2 = dest1;
  53.  
  54. dest1->i = 85;
  55. dest2->i = 37;
  56. }
  57.  
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
3
3
3 <- copy / orig -> 3
5 <- copy / orig -> 2
Destructor here; i = 37
Destructor here; i = 85