From 6f0d40508286afc8cdd72a0b5f807d5c2a589cfc Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Fri, 4 Jun 2010 16:33:08 +0200 Subject: Initial implementation --- odb/shared-ptr-traits.hxx | 119 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 odb/shared-ptr-traits.hxx (limited to 'odb/shared-ptr-traits.hxx') diff --git a/odb/shared-ptr-traits.hxx b/odb/shared-ptr-traits.hxx new file mode 100644 index 0000000..a1d5146 --- /dev/null +++ b/odb/shared-ptr-traits.hxx @@ -0,0 +1,119 @@ +// file : odb/shared-ptr-traits.hxx +// author : Boris Kolpackov +// copyright : Copyright (c) 2009-2010 Code Synthesis Tools CC +// license : GNU GPL v2; see accompanying LICENSE file + +#ifndef ODB_SHARED_PTR_TRAITS_HXX +#define ODB_SHARED_PTR_TRAITS_HXX + +#include // operators new/delete +#include // std::size_t + +#include + +namespace odb +{ + template + class shared_ptr_traits; + + // Default implementation that should work for any sensible smart + // pointer with one template argument (object type). The only + // assumptions that we make are the availability of operator-> and + // operator*, and that the former does not throw if the pointer is + // NULL. + // + template class P> + class shared_ptr_traits< P > + { + public: + typedef T type; + typedef P shared_ptr; + + // Return underlying pointer, including NULL. + // + static type* + get_ptr (const shared_ptr& p) + { + return p.operator-> (); + } + + // Return reference to the pointed-to object. + // + static type& + get_ref (const shared_ptr& p) + { + return *p; + } + + // Return true if the pointer is NULL. + // + static bool + null_ptr (const shared_ptr& p) + { + return get_ptr () == 0; + } + + public: + // Allocate memory for a shared object. + // + static void* + allocate (std::size_t n) + { + return operator new (n); + } + + // Free memory allocated for a shared object. This functions is + // only called if the constructor of the object being created + // fails. Otherwise, shared_ptr is used to delete the object + // and free the memory. This behavior is identical to the one + // used by operator delete overloading. + // + static void + free (void* p) + { + operator delete (p); + } + }; + + // Specialization for odb::shared_ptr. + // + template + class shared_ptr_traits< shared_ptr > + { + public: + typedef T type; + typedef odb::shared_ptr shared_ptr; + + static type* + get_ptr (const shared_ptr& p) + { + return p.get (); + } + + static type& + get_ref (const shared_ptr& p) + { + return *p; + } + + static bool + null_ptr (const shared_ptr& p) + { + return !p; + } + + static void* + allocate (std::size_t n) + { + return operator new (n, shared); + } + + static void + free (void* p) + { + operator delete (p, shared); + } + }; +} + +#endif // ODB_SHARED_PTR_TRAITS_HXX -- cgit v1.1