alloc_utils.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 alloc_utils.h
00026  *  Classes providing raw memory allocation and deallocation support.
00027  *
00028  *  Copyright (C) 2011 Max-Planck-Society
00029  *  \author Martin Reinecke
00030  */
00031 
00032 #ifndef PLANCK_ALLOC_UTILS_H
00033 #define PLANCK_ALLOC_UTILS_H
00034 
00035 #include <cstdlib>
00036 #include "datatypes.h"
00037 
00038 template <typename T> class normalAlloc__
00039   {
00040   public:
00041     T *alloc(tsize sz) const { return (sz>0) ? new T[sz] : 0; }
00042     void dealloc (T *ptr) const { delete[] ptr; }
00043   };
00044 
00045 template <typename T, int align> class alignAlloc__
00046   {
00047   public:
00048     T *alloc(tsize sz) const
00049       {
00050       using namespace std;
00051       if (sz==0) return 0;
00052       planck_assert((align&(align-1))==0,"alignment must be power of 2");
00053       void *res;
00054 /* OSX up to version 10.5 does not define posix_memalign(), but fortunately
00055    the normal malloc() returns 16 byte aligned storage */
00056 #ifdef __APPLE__
00057       planck_assert(align<=16, "bad alignment requested");
00058       res=malloc(sz*sizeof(T));
00059       planck_assert(res!=0,"error in malloc()");
00060 #else
00061       planck_assert(posix_memalign(&res,align,sz*sizeof(T))==0,
00062         "error in posix_memalign()");
00063 #endif
00064       return static_cast<T *>(res);
00065       }
00066     void dealloc(T *ptr) const
00067       {
00068       using namespace std;
00069       free(ptr);
00070       }
00071   };
00072 
00073 #endif

Generated on Wed Apr 24 11:31:16 2013 for LevelS C++ support library