forked from scylladb/scylladb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrefcounted.hh
44 lines (38 loc) · 911 Bytes
/
refcounted.hh
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
/*
* Copyright (C) 2023-present ScyllaDB
*/
/*
* SPDX-License-Identifier: LicenseRef-ScyllaDB-Source-Available-1.0
*/
#include <cstdint>
#include <cassert>
#pragma once
namespace utils {
// Aborts the program if destroyed with existing references.
class refcounted {
mutable uint64_t _count = 0;
public:
refcounted() = default;
refcounted(refcounted&&) = delete;
~refcounted() noexcept {
assert(_count == 0);
}
template <typename T>
class ref {
T& _target;
public:
ref(T& t) noexcept : _target(t) {
static_cast<const refcounted&>(_target)._count += 1;
}
~ref() noexcept {
static_cast<const refcounted&>(_target)._count -= 1;
}
T* operator->() const noexcept {
return &_target;
}
T& operator*() const noexcept {
return _target;
}
};
};
}