safe_ptr.h

Go to the documentation of this file.
00001 /*
00002  *  This file is part of libcxxsupport.
00003  *
00004  *  libcxxsupport is free software; you can redistribute it and/or modify
00005  *  it under the terms of the GNU General Public License as published by
00006  *  the Free Software Foundation; either version 2 of the License, or
00007  *  (at your option) any later version.
00008  *
00009  *  libcxxsupport is distributed in the hope that it will be useful,
00010  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  *  GNU General Public License for more details.
00013  *
00014  *  You should have received a copy of the GNU General Public License
00015  *  along with libcxxsupport; if not, write to the Free Software
00016  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
00017  */
00018 
00019 /*
00020  *  libcxxsupport is being developed at the Max-Planck-Institut fuer Astrophysik
00021  *  and financially supported by the Deutsches Zentrum fuer Luft- und Raumfahrt
00022  *  (DLR).
00023  */
00024 
00025 /*! \file safe_ptr.h
00026  *  Pointer wrapper for better exception safety and leakage prevention
00027  *
00028  *  Copyright (C) 2005-2015 Max-Planck-Society
00029  *  \author Martin Reinecke
00030  */
00031 
00032 #ifndef PLANCK_SAFE_PTR_H
00033 #define PLANCK_SAFE_PTR_H
00034 
00035 #if (__cplusplus>=201103L)
00036 
00037 #include <memory>
00038 template<typename T> using safe_ptr = std::unique_ptr<T>;
00039 
00040 #else
00041 
00042 #include "error_handling.h"
00043 
00044 template <typename T> class safe_ptr
00045   {
00046   private:
00047     T *p;
00048     bool set;
00049 
00050     // forbid copying of safe_ptrs, at least until we know how to do it
00051     safe_ptr (const safe_ptr &) {}
00052     safe_ptr &operator= (const safe_ptr &) { return *this; }
00053 
00054   public:
00055     safe_ptr() : p(0), set(false) {}
00056     safe_ptr (T *p2) : p(p2), set(true) {}
00057     ~safe_ptr() { delete p; }
00058 
00059     void reset (T *p2)
00060       {
00061       planck_assert (!set, "safe_ptr: already set");
00062       set = true;
00063       p=p2;
00064       }
00065 
00066     void reset()
00067       {
00068       delete p;
00069       p=0;
00070       set=false;
00071       }
00072 
00073     T * get() const
00074       { return p; }
00075 
00076     operator T*() { return p; }
00077     operator const T*() const { return p; }
00078     T *operator->() { return p; }
00079     const T *operator->() const { return p; }
00080   };
00081 
00082 #endif
00083 
00084 #endif

Generated on Thu Oct 8 14:48:51 2015 for LevelS C++ support library