summaryrefslogtreecommitdiffstats
path: root/logic/QObjectPtr.h
blob: 32e59bd9c5f494bc583d3946e17a7fe614b9f6a1 (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
#pragma once

#include <memory>

/**
 * A pointer class with the usual shared pointer semantics intended for derivates of QObject
 * Calls deleteLater() instead of destroying the contained object immediately
 */
template <typename T>
class QObjectPtr
{
public:
	QObjectPtr(){}
	QObjectPtr(T * wrap)
	{
		reset(wrap);
	}
	QObjectPtr(const QObjectPtr<T>& other)
	{
		m_ptr = other.m_ptr;
	}
	template<typename Derived>
	QObjectPtr(const QObjectPtr<Derived> &other)
	{
		m_ptr = other.unwrap();
	}

public:
	void reset(T * wrap)
	{
		using namespace std::placeholders;
		m_ptr.reset(wrap, std::bind(&QObject::deleteLater, _1));
	}
	void reset()
	{
		m_ptr.reset();
	}
	T * get() const
	{
		return m_ptr.get();
	}
	T * operator->() const
	{
		return m_ptr.get();
	}
	T & operator*() const
	{
		return *m_ptr.get();
	}
	operator bool() const
	{
		return m_ptr.get() != nullptr;
	}
	const std::shared_ptr <T> unwrap() const
	{
		return m_ptr;
	}

private:
	std::shared_ptr <T> m_ptr;
};