AK: Add NeverDestroyed<T>, for things that should never be destroyed

This template allows you to define static globals without having them
destroyed on exit.
This commit is contained in:
Andreas Kling 2019-12-26 22:12:45 +01:00
parent b830639912
commit f607cab235

36
AK/NeverDestroyed.h Normal file
View file

@ -0,0 +1,36 @@
#pragma once
#include <AK/Noncopyable.h>
#include <AK/StdLibExtras.h>
namespace AK {
template<typename T>
class NeverDestroyed {
AK_MAKE_NONCOPYABLE(NeverDestroyed)
AK_MAKE_NONMOVABLE(NeverDestroyed)
public:
template<typename... Args>
NeverDestroyed(Args... args)
{
new (storage) T(forward<Args>(args)...);
}
~NeverDestroyed() = default;
T* operator->() { return &get(); }
const T* operator->() const { return &get(); }
T& operator*() { return get(); }
const T* operator*() const { return get(); }
T& get() { return reinterpret_cast<T&>(storage); }
const T& get() const { return reinterpret_cast<T&>(storage); }
private:
alignas(T) u8 storage[sizeof(T)];
};
}
using AK::NeverDestroyed;