CppCMS
booster/copy_ptr.h
00001 //
00002 //  Copyright (C) 2009-2012 Artyom Beilis (Tonkikh)
00003 //
00004 //  Distributed under the Boost Software License, Version 1.0. (See
00005 //  accompanying file LICENSE_1_0.txt or copy at
00006 //  http://www.boost.org/LICENSE_1_0.txt)
00007 //
00008 #ifndef BOOSTER_UTIL_COPY_PTR_H
00009 #define BOOSTER_UTIL_COPY_PTR_H
00010 
00011 namespace booster { 
00012 
00021         template<typename T>
00022         class copy_ptr {
00023                 T *ptr_;
00024         public:
00025                 copy_ptr() : ptr_(0) {}
00026                 explicit copy_ptr(T *v) : ptr_(v) {}
00027                 copy_ptr(copy_ptr const &other) :
00028                         ptr_(other.ptr_ ? new T(*other.ptr_) : 0)
00029                 {
00030                 }
00031                 copy_ptr const &operator=(copy_ptr const &other)
00032                 {
00033                         if(this != &other) {
00034                                 copy_ptr tmp(other);
00035                                 swap(tmp);
00036                         }
00037                         return *this;
00038                 }
00039                 ~copy_ptr() {
00040                         if(ptr_) delete ptr_;
00041                 }
00042 
00043                 T const *get() const { return ptr_; }
00044                 T *get() { return ptr_; }
00045 
00046                 T const &operator *() const { return *ptr_; }
00047                 T &operator *() { return *ptr_; }
00048                 T const *operator->() const { return ptr_; }
00049                 T *operator->() { return ptr_; }
00050                 T *release() { T *tmp=ptr_; ptr_=0; return tmp; }
00051                 void reset(T *p=0)
00052                 {
00053                         if(ptr_) delete ptr_;
00054                         ptr_=p;
00055                 }
00056                 void swap(copy_ptr &other)
00057                 {
00058                         T *tmp=other.ptr_;
00059                         other.ptr_=ptr_;
00060                         ptr_=tmp;
00061                 }
00062         };
00063 
00064 } // booster
00065 
00066 #endif