fork download
  1. // pimpl template courtesy of Matthieu
  2. template <class T>
  3. class pimpl
  4. {
  5. public:
  6. /**
  7.   * Types
  8.   */
  9. typedef const T const_value;
  10. typedef T* pointer;
  11. typedef const T* const_pointer;
  12. typedef T& reference;
  13. typedef const T& const_reference;
  14.  
  15. /**
  16.   * Gang of Four
  17.   */
  18. pimpl() : m_value(new T) {}
  19. explicit pimpl(const_reference v) : m_value(new T(v)) {}
  20.  
  21. pimpl(const pimpl& rhs) : m_value(new T(*(rhs.m_value))) {}
  22.  
  23. pimpl& operator=(const pimpl& rhs)
  24. {
  25. pimpl tmp(rhs);
  26. swap(tmp);
  27. return *this;
  28. } // operator=
  29.  
  30. ~pimpl() { delete m_value; }
  31.  
  32. void swap(pimpl& rhs)
  33. {
  34. pointer temp(rhs.m_value);
  35. rhs.m_value = m_value;
  36. m_value = temp;
  37. } // swap
  38.  
  39. /**
  40.   * Data access
  41.   */
  42. pointer get() { return m_value; }
  43. const_pointer get() const { return m_value; }
  44.  
  45. reference operator*() { return *m_value; }
  46. const_reference operator*() const { return *m_value; }
  47.  
  48. pointer operator->() { return m_value; }
  49. const_pointer operator->() const { return m_value; }
  50.  
  51. private:
  52. pointer m_value;
  53. }; // class pimpl<T>
  54.  
  55. // Swap
  56. template <class T>
  57. void swap(pimpl<T>& lhs, pimpl<T>& rhs) { lhs.swap(rhs); }
  58.  
  59. // Test Case
  60. // c.h -------------------
  61. class C {
  62.  
  63. public:
  64. int getI() const;
  65. void setI( int i );
  66.  
  67. private:
  68. struct Private;
  69. pimpl<Private> d;
  70. };
  71.  
  72. // c.cpp ------------------
  73. struct C::Private {
  74. int i;
  75. };
  76.  
  77. int C::getI() const {
  78. return d->i;
  79. }
  80.  
  81. void C::setI( int i ) {
  82. d->i = i;
  83. }
  84.  
  85. #include <iostream>
  86. int main()
  87. {
  88. C a;
  89. a.setI( 4 );
  90. C b = a;
  91. b.setI( 5 );
  92.  
  93. std::cout << a.getI() << b.getI() << std::endl;
  94. }
  95.  
Success #stdin #stdout 0.02s 2812KB
stdin
Standard input is empty
stdout
45