CppCMS
booster/clone_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_CLONE_PTR_H
00009 #define BOOSTER_CLONE_PTR_H
00010 
00011 namespace booster {
00012         
00017         template<typename T>
00018         class clone_ptr {
00019                 T *ptr_;
00020         public:
00021                 clone_ptr() : ptr_(0) {}
00022                 explicit clone_ptr(T *v) : ptr_(v) {}
00023                 clone_ptr(clone_ptr const &other) : ptr_(0)
00024                 {
00025                         if(other.ptr_)
00026                                 ptr_=other.ptr_->clone();
00027                 }
00028                 clone_ptr const &operator=(clone_ptr const &other)
00029                 {
00030                         if(this != &other) {
00031                                 clone_ptr tmp(other);
00032                                 swap(tmp);
00033                         }
00034                         return *this;
00035                 }
00036                 ~clone_ptr() {
00037                         if(ptr_) delete ptr_;
00038                 }
00039 
00040                 T *get() const { return ptr_; }
00041                 T &operator *() const { return *ptr_; }
00042                 T *operator->() const { return ptr_; }
00043 
00044                 T *release() { T *tmp=ptr_; ptr_=0; return tmp; }
00045                 void reset(T *p=0)
00046                 {
00047                         if(ptr_) delete ptr_;
00048                         ptr_=p;
00049                 }
00050                 void swap(clone_ptr &other)
00051                 {
00052                         T *tmp=other.ptr_;
00053                         other.ptr_=ptr_;
00054                         ptr_=tmp;
00055                 }
00056         };
00057 
00058 } // booster
00059 
00060 #endif