Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 12:53:29

0001 #ifndef DeepCopyPointer_H
0002 #define DeepCopyPointer_H
0003 
0004 #include <algorithm>
0005 
0006 /** A "smart" pointer that implements deep copy and ownership.
0007  *  In other words, when the pointer is copied it copies the 
0008  *  object it points to using "new". It also deletes the
0009  *  object it points to when it is deleted.
0010  *  Very useful for use as private data member of a class:
0011  *  it handles the copy construction, assignment, and destruction.
0012  */
0013 
0014 template <class T>
0015 class DeepCopyPointer {
0016 public:
0017   ~DeepCopyPointer() { delete theData; }
0018 
0019   DeepCopyPointer() : theData(0) {}
0020 
0021   DeepCopyPointer(T* t) : theData(t) {}
0022 
0023   DeepCopyPointer(const DeepCopyPointer& other) {
0024     if (other.theData)
0025       theData = new T(*other);
0026     else
0027       theData = 0;
0028   }
0029 
0030   DeepCopyPointer& operator=(const DeepCopyPointer& other) {
0031     if (theData != other.theData) {
0032       delete theData;
0033       if (other.theData)
0034         theData = new T(*other);
0035       else
0036         theData = 0;
0037     }
0038     return *this;
0039   }
0040 
0041   // straight from http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2027.html
0042   DeepCopyPointer(DeepCopyPointer&& other) : theData(other.theData) { other.theData = 0; }
0043   DeepCopyPointer& operator=(DeepCopyPointer&& other) {
0044     std::swap(theData, other.theData);
0045     return *this;
0046   }
0047 
0048   /// Assing a new bare pointer to this DeepCopyPointer, taking ownership of it.
0049   /// The old content of this DeepCopyPointer is deleted
0050   void replaceWith(T* otherP) {
0051     if (theData != otherP) {
0052       delete theData;
0053       theData = otherP;
0054     }
0055   }
0056 
0057   // assume that the replacement object is of the very same class!
0058   // at the moment all the work is done by the client i.e.
0059   // call the distructor
0060   // new in place
0061   // with c++0X a templated method can encasulate it all here...
0062   T* replaceInplace() { return theData; }
0063 
0064   T& operator*() { return *theData; }
0065   const T& operator*() const { return *theData; }
0066 
0067   T* operator->() { return theData; }
0068   const T* operator->() const { return theData; }
0069 
0070   /// to allow test like " if (p) {...}"
0071   operator bool() const { return theData != 0; }
0072 
0073   /// to allow test like " if (p == &someT) {...}"
0074   bool operator==(const T* otherP) const { return theData == otherP; }
0075 
0076 private:
0077   T* theData;
0078 };
0079 
0080 #endif  // DeepCopyPointer_H