summaryrefslogtreecommitdiff
path: root/src/common/include/gudhi/Simple_object_pool.h
blob: 164849e1719aa135b7b2a5c814cccd03ca7bf5c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*    This file is part of the Gudhi Library. The Gudhi library
 *    (Geometric Understanding in Higher Dimensions) is a generic C++
 *    library for computational topology.
 *
 *    Author(s):       Marc Glisse
 *
 *    Copyright (C) 2015 Inria
 *
 *    Modification(s):
 *      - YYYY/MM Author: Description of the modification
 */

#ifndef SIMPLE_OBJECT_POOL_H_
#define SIMPLE_OBJECT_POOL_H_

#include <boost/pool/pool.hpp>
#include <utility>

namespace Gudhi {

/** \private
 * This is a simpler version of boost::object_pool, that requires
 * that users explicitly destroy all objects. This lets the
 * performance scale much better, see
 * https://svn.boost.org/trac/boost/ticket/3789 .
 */
template <class T>
class Simple_object_pool : protected boost::pool<boost::default_user_allocator_malloc_free> {
 protected:
  typedef boost::pool<boost::default_user_allocator_malloc_free> Base;
  typedef T* pointer;

  Base& base() {
    return *this;
  }

  Base const& base()const {
    return *this;
  }

 public:
  typedef T element_type;
  typedef boost::default_user_allocator_malloc_free user_allocator;
  typedef typename Base::size_type size_type;
  typedef typename Base::difference_type difference_type;

  template<class...U>
  Simple_object_pool(U&&...u) : Base(sizeof (T), std::forward<U>(u)...) { }

  template<class...U>
  pointer construct(U&&...u) {
    void* p = base().malloc BOOST_PREVENT_MACRO_SUBSTITUTION();
    assert(p);
    try {
      new(p) T(std::forward<U>(u)...);
    }    catch (...) {
      base().free BOOST_PREVENT_MACRO_SUBSTITUTION(p);
      throw;
    }
    return static_cast<pointer> (p);
  }

  void destroy(pointer p) {
    p->~T();
    base().free BOOST_PREVENT_MACRO_SUBSTITUTION(p);
  }
};

}  // namespace Gudhi

#endif  // SIMPLE_OBJECT_POOL_H_