mpd/src/util/Manual.hxx

97 lines
1.8 KiB
C++
Raw Normal View History

// SPDX-License-Identifier: BSD-2-Clause
// author: Max Kellermann <max.kellermann@gmail.com>
2013-01-30 23:48:34 +01:00
2022-05-31 16:10:28 +02:00
#pragma once
2013-01-30 23:48:34 +01:00
#include <cassert>
2013-01-30 23:48:34 +01:00
#include <new>
#include <type_traits>
#include <utility>
2013-01-30 23:48:34 +01:00
/**
* Container for an object that gets constructed and destructed
* manually. The object is constructed in-place, and therefore
* without allocation overhead. It can be constructed and destructed
* repeatedly.
*/
template<class T>
class Manual {
using Storage = std::aligned_storage_t<sizeof(T), alignof(T)>;
Storage storage;
2013-01-30 23:48:34 +01:00
#ifndef NDEBUG
2017-07-05 12:12:41 +02:00
bool initialized = false;
2013-01-30 23:48:34 +01:00
#endif
public:
2022-05-31 16:08:47 +02:00
using value_type = T;
using reference = T &;
using const_reference = const T &;
using pointer = T *;
using const_pointer = const T *;
2013-01-30 23:48:34 +01:00
#ifndef NDEBUG
2022-05-31 16:10:28 +02:00
~Manual() noexcept {
2013-01-30 23:48:34 +01:00
assert(!initialized);
}
#endif
2018-08-20 15:35:43 +02:00
/**
* Cast a value reference to the containing Manual instance.
*/
2022-05-31 16:08:47 +02:00
static constexpr Manual<T> &Cast(reference value) noexcept {
2018-08-20 15:35:43 +02:00
return reinterpret_cast<Manual<T> &>(value);
}
2013-01-30 23:48:34 +01:00
template<typename... Args>
void Construct(Args&&... args) {
assert(!initialized);
::new(&storage) T(std::forward<Args>(args)...);
2013-01-30 23:48:34 +01:00
#ifndef NDEBUG
initialized = true;
#endif
}
2022-05-31 16:10:28 +02:00
void Destruct() noexcept {
2013-01-30 23:48:34 +01:00
assert(initialized);
2022-05-31 16:08:47 +02:00
reference t = Get();
2014-12-09 23:08:53 +01:00
t.T::~T();
2013-01-30 23:48:34 +01:00
#ifndef NDEBUG
initialized = false;
#endif
}
2022-05-31 16:08:47 +02:00
reference Get() noexcept {
2014-12-09 23:08:22 +01:00
assert(initialized);
return *std::launder(reinterpret_cast<pointer>(&storage));
2013-01-30 23:48:34 +01:00
}
2022-05-31 16:08:47 +02:00
const_reference Get() const noexcept {
2014-12-09 23:08:22 +01:00
assert(initialized);
return *std::launder(reinterpret_cast<const_pointer>(&storage));
2013-01-30 23:48:34 +01:00
}
2022-05-31 16:08:47 +02:00
operator reference() noexcept {
return Get();
}
2022-05-31 16:08:47 +02:00
operator const_reference() const noexcept {
return Get();
}
2022-05-31 16:08:47 +02:00
pointer operator->() noexcept {
return &Get();
2013-01-30 23:48:34 +01:00
}
2022-05-31 16:08:47 +02:00
const_pointer operator->() const noexcept {
return &Get();
2013-01-30 23:48:34 +01:00
}
};