fork download
  1. #include <memory>
  2.  
  3. class interface_d
  4. {
  5. public:
  6. virtual ~interface_d() {}
  7. virtual interface_d* clone() const = 0;
  8.  
  9. };
  10.  
  11. class d1
  12. : public interface_d
  13. {
  14. public:
  15. d1() : interface_d(), m_x(new int) {}
  16. d1(const d1 &rhs) : interface_d(), m_x(new int(*rhs.m_x)) {}
  17. virtual ~d1()
  18. {
  19. delete m_x;
  20. }
  21.  
  22. virtual interface_d* clone() const
  23. {
  24. return new d1(*this);
  25. }
  26.  
  27. private:
  28. int *m_x;
  29. };
  30.  
  31. class base
  32. {
  33. public:
  34. base(std::unique_ptr<interface_d> impl) : m_impl(std::move(impl)) {}
  35. base(const base &rhs) : m_impl(rhs.m_impl->clone()) {}
  36. base& operator=(const base &rhs)
  37. {
  38. if (this != &rhs)
  39. {
  40. std::unique_ptr<interface_d> tmp(rhs.m_impl->clone());
  41. std::swap(m_impl, tmp);
  42. }
  43. return *this;
  44. }
  45. ~base()
  46. {
  47. // ... do something before clear impl
  48. m_impl.reset();
  49. // ... do something after clear impl
  50. }
  51.  
  52. private:
  53. std::unique_ptr<interface_d> m_impl;
  54. };
  55.  
  56. int main() {
  57.  
  58. base x(std::unique_ptr<d1>(new d1));
  59. base y(x);
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Standard output is empty