SharedPtr.hpp 1.3 KB
Newer Older
1
2
3
#pragma once

#include <memory>
Praetorius, Simon's avatar
Praetorius, Simon committed
4
#include <type_traits>
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
#include <utility>

#include <dune/common/shared_ptr.hh>

#include <amdis/common/TypeTraits.hpp>

namespace AMDiS
{
  /**
   *  Helper function converting the argument into a shared_ptr. The following cases are handled:
   *  - objects passed as rvalue references are used to construct a new shared_ptr
   *  - objects passed as references are used to construct a shared_ptr with a null deleter that
   *    does nothing when the pointer is destroyed, using the stored base pointer in case of a
   *    unique_ptr argument
   *  - shared_ptr are simply forwarded
   */
  template <class T>
  std::shared_ptr<T> wrap_or_share(T& t)
  {
    return Dune::stackobject_to_shared_ptr(t);
  }

  template<class T>
  std::shared_ptr<T> wrap_or_share(T&& t)
  {
    return std::make_shared<T>(FWD(t));
  }

  template <class T>
Praetorius, Simon's avatar
Praetorius, Simon committed
34
  std::shared_ptr<T> wrap_or_share(T* t)
35
  {
36
    static_assert(not std::is_pointer_v<T*>,
Praetorius, Simon's avatar
Praetorius, Simon committed
37
      "Raw pointers must be wrapped into smart pointers or references to clarify ownership");
38
39
40
41
42
43
44
45
46
  }

  template <class T>
  std::shared_ptr<T> wrap_or_share(std::shared_ptr<T> t)
  {
    return std::move(t);
  }

  template <class T>
Praetorius, Simon's avatar
Praetorius, Simon committed
47
  std::shared_ptr<T> wrap_or_share(std::unique_ptr<T> t)
48
49
50
51
52
  {
    return std::shared_ptr<T>(std::move(t));
  }

} // end namespace AMDiS