The Battle for Wesnoth  1.15.9+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 "global.hpp"
17 
18 #include <memory>
19 #include <stdexcept>
20 
21 namespace utils {
22 
23 template <typename T>
25 {
26  std::shared_ptr<T> m_ptr;
27 
28 public:
29  template<typename Y>
31  : m_ptr(p.m_ptr)
32  { }
33  template<typename Y>
35  : m_ptr(std::move(p.m_ptr))
36  { }
37  template<typename Y>
38  explicit shared_reference(const std::shared_ptr<Y>& p)
39  : m_ptr(p)
40  {
41  if(!p) {
42  throw std::invalid_argument("invalid shared_reference");
43  }
44  }
45  template<typename Y>
46  explicit shared_reference(std::shared_ptr<Y>&& p)
47  : m_ptr(p)
48  {
49  if(!p) {
50  throw std::invalid_argument("invalid shared_reference");
51  }
52  }
53 
54  template<typename Y>
56  {
57  m_ptr = std::move(p.m_ptr);
58  return *this;
59  }
60  template<typename Y>
62  {
63  m_ptr = p.m_ptr;
64  return *this;
65  }
66 
67  ~shared_reference() = default;
68 
69  operator std::shared_ptr<T>()
70  { return m_ptr; }
71 
72  T* operator->() { return m_ptr.get(); }
73  const T* operator->() const { return m_ptr.get(); }
74 
75  T& operator*() { return *m_ptr.get(); }
76  const T& operator*() const { return *m_ptr.get(); }
77 
78  template <typename XT, typename...XTypes>
79  friend shared_reference<XT> make_shared_reference(XTypes&&...args);
80 
81 };
82 
83 
84 template <typename T, typename...Types>
86 {
87  return shared_reference<T>(std::make_shared<T>(std::forward<Types>(args)...));
88 }
89 
90 
91 } // 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)