libqi  1.14.5
qi/shared_ptr.hpp
00001 /*
00002  * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
00003  * Use of this source code is governed by a BSD-style license that can be
00004  * found in the COPYING file.
00005  */
00006 
00007 #pragma once
00008 
00009 #ifndef _LIBQI_QI_SHARED_PTR_HPP_
00010 #define _LIBQI_QI_SHARED_PTR_HPP_
00011 
00012 #include <qi/atomic.hpp>
00013 #include <qi/log.hpp>
00014 
00015 namespace qi
00016 {
00017   template <typename T>
00018   class SharedPtr
00019   {
00020   public:
00021     SharedPtr(T *ptr)
00022       : _ptr(ptr)
00023       , _refcount(new qi::atomic<long>(1))
00024     {
00025     }
00026 
00027     ~SharedPtr()
00028     {
00029       if (--(*_refcount) == 0)
00030       {
00031         delete _ptr;
00032         delete _refcount;
00033       }
00034     }
00035 
00036     SharedPtr(const SharedPtr<T> &sp)
00037     {
00038       /*
00039        * Note that this line is racy.
00040        * If someone is deleting _refcount,
00041        * it cannot be used below.
00042        */
00043       if (++(*_refcount) != 1)
00044       {
00045         _ptr = sp._ptr;
00046       }
00047       else
00048       {
00049         qiLogDebug("qi.log.shared_ptr")
00050                   << "tried to copy a shared pointer targeted for deletion"
00051                   << std::endl;
00052       }
00053     }
00054 
00055     SharedPtr& operator=(SharedPtr<T> &sp)
00056     {
00057       // release the current pointer
00058       if (--(*_refcount) == 0)
00059       {
00060         delete _ptr;
00061         delete _refcount;
00062       }
00063       _ptr = sp._ptr;
00064       _refcount = sp._refcount;
00065     }
00066 
00067     T &operator*() const
00068     {
00069       return *_ptr;
00070     }
00071 
00072     T *operator->() const
00073     {
00074       return _ptr;
00075     }
00076 
00077   private:
00078     T                *_ptr;
00079     qi::atomic<long> *_refcount;
00080   };
00081 }
00082 
00083 #endif // _LIBQI_QI_SHARED_PTR_HPP_
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines