JsonCpp project page JsonCpp home page

include/json/allocator.h
Go to the documentation of this file.
00001 // Copyright 2007-2010 Baptiste Lepilleur
00002 // Distributed under MIT license, or public domain if desired and
00003 // recognized in your jurisdiction.
00004 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
00005 
00006 #ifndef CPPTL_JSON_ALLOCATOR_H_INCLUDED
00007 #define CPPTL_JSON_ALLOCATOR_H_INCLUDED
00008 
00009 #include <cstring>
00010 #include <memory>
00011 
00012 namespace Json {
00013 template<typename T>
00014 class SecureAllocator {
00015    public:
00016       // Type definitions
00017       using value_type      = T;
00018       using pointer         = T*;
00019       using const_pointer   = const T*;
00020       using reference       = T&;
00021       using const_reference = const T&;
00022       using size_type       = std::size_t;
00023       using difference_type = std::ptrdiff_t;
00024 
00028       pointer allocate(size_type n) {
00029          // allocate using "global operator new"
00030          return static_cast<pointer>(::operator new(n * sizeof(T)));
00031       }
00032 
00040       void deallocate(volatile pointer p, size_type n) {
00041          std::memset(p, 0, n * sizeof(T));
00042          // free using "global operator delete"
00043          ::operator delete(p);
00044       }
00045 
00049       template<typename... Args>
00050       void construct(pointer p, Args&&... args) {
00051          // construct using "placement new" and "perfect forwarding"
00052          ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...);
00053       }
00054 
00055       size_type max_size() const {
00056          return size_t(-1) / sizeof(T);
00057       }
00058 
00059       pointer address( reference x ) const {
00060          return std::addressof(x);
00061       }
00062 
00063       const_pointer address( const_reference x ) const {
00064          return std::addressof(x);
00065       }
00066 
00070       void destroy(pointer p) {
00071          // destroy using "explicit destructor"
00072          p->~T();
00073       }
00074 
00075       // Boilerplate
00076       SecureAllocator() {}
00077       template<typename U> SecureAllocator(const SecureAllocator<U>&) {}
00078       template<typename U> struct rebind { using other = SecureAllocator<U>; };
00079 };
00080 
00081 
00082 template<typename T, typename U>
00083 bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) {
00084    return true;
00085 }
00086 
00087 template<typename T, typename U>
00088 bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) {
00089    return false;
00090 }
00091 
00092 } //namespace Json
00093 
00094 #endif // CPPTL_JSON_ALLOCATOR_H_INCLUDED