The Battle for Wesnoth  1.19.8+dev
lua_ptr.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2020 - 2024
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #pragma once
16 
17 #include <memory>
18 template<typename T>
19 class lua_ptr;
20 
21 template<typename T>
23 {
24 public:
25  enable_lua_ptr(T* tp) : self_(std::make_shared<T*>(tp)) {}
27  {
28  *self_ = static_cast<T*>(this);
29  }
31  {
32  self_ = std::move(o.self_);
33  *self_ = static_cast<T*>(this);
34  }
35 private:
36  enable_lua_ptr(const enable_lua_ptr& o) = delete;
38  friend class lua_ptr<T>;
39  std::shared_ptr<T*> self_;
40 };
41 
42 /** Tmust inherit enable_lua_ptr<T> */
43 template<typename T>
44 class lua_ptr
45 {
46 public:
48  T* get_ptr()
49  {
50  if(auto pp = self_.lock()) {
51  return *pp;
52  }
53  return nullptr;
54  }
56  {
57  return get_ptr();
58  }
59  operator bool() const
60  {
61  return bool(self_.lock());
62  }
63  bool operator!() const
64  {
65  return !operator bool();
66  }
67  std::weak_ptr<T*> self_;
68 };
enable_lua_ptr(enable_lua_ptr &&o)
Definition: lua_ptr.hpp:26
enable_lua_ptr(const enable_lua_ptr &o)=delete
std::shared_ptr< T * > self_
Definition: lua_ptr.hpp:39
enable_lua_ptr & operator=(enable_lua_ptr &&o)
Definition: lua_ptr.hpp:30
enable_lua_ptr(T *tp)
Definition: lua_ptr.hpp:25
Tmust inherit enable_lua_ptr<T>
Definition: lua_ptr.hpp:45
bool operator!() const
Definition: lua_ptr.hpp:63
T * operator->()
Definition: lua_ptr.hpp:55
lua_ptr(enable_lua_ptr< T > &o)
Definition: lua_ptr.hpp:47
std::weak_ptr< T * > self_
Definition: lua_ptr.hpp:67
T * get_ptr()
Definition: lua_ptr.hpp:48