The Battle for Wesnoth  1.15.12+dev
shared_reference.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2020 the Battle for Wesnoth Project https://www.wesnoth.org/
3 
4  This program is free software; you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation; either version 2 of the License, or
7  (at your option) any later version.
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY.
10 
11  See the COPYING file for more details.
12 */
13 
14 #pragma once
15 
16 #include <memory>
17 #include <stdexcept>
18 
19 namespace utils {
20 
21 template <typename T>
23 {
24  std::shared_ptr<T> m_ptr;
25 
26 public:
27  template<typename Y>
29  : m_ptr(p.m_ptr)
30  { }
31  template<typename Y>
33  : m_ptr(std::move(p.m_ptr))
34  { }
35  template<typename Y>
36  explicit shared_reference(const std::shared_ptr<Y>& p)
37  : m_ptr(p)
38  {
39  if(!p) {
40  throw std::invalid_argument("invalid shared_reference");
41  }
42  }
43  template<typename Y>
44  explicit shared_reference(std::shared_ptr<Y>&& p)
45  : m_ptr(p)
46  {
47  if(!p) {
48  throw std::invalid_argument("invalid shared_reference");
49  }
50  }
51 
52  template<typename Y>
54  {
55  m_ptr = std::move(p.m_ptr);
56  return *this;
57  }
58  template<typename Y>
60  {
61  m_ptr = p.m_ptr;
62  return *this;
63  }
64 
65  ~shared_reference() = default;
66 
67  operator std::shared_ptr<T>()
68  { return m_ptr; }
69 
70  T* operator->() { return m_ptr.get(); }
71  const T* operator->() const { return m_ptr.get(); }
72 
73  T& operator*() { return *m_ptr.get(); }
74  const T& operator*() const { return *m_ptr.get(); }
75 
76  template <typename XT, typename...XTypes>
77  friend shared_reference<XT> make_shared_reference(XTypes&&...args);
78 
79 };
80 
81 
82 template <typename T, typename...Types>
84 {
85  return shared_reference<T>(std::make_shared<T>(std::forward<Types>(args)...));
86 }
87 
88 
89 } // namespace utils
shared_reference & operator=(const shared_reference< Y > &p)
const T & operator*() const
shared_reference(const shared_reference< Y > &p)
friend shared_reference< XT > make_shared_reference(XTypes &&...args)
STL namespace.
std::shared_ptr< T > m_ptr
shared_reference(std::shared_ptr< Y > &&p)
const T * operator->() const
shared_reference & operator=(shared_reference< Y > &&p)
mock_party p
shared_reference(const std::shared_ptr< Y > &p)
shared_reference(shared_reference< Y > &&p)