Skip to content

Instantly share code, notes, and snippets.

@xaxxon
Created February 5, 2018 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xaxxon/cbca2a4c89b8507231a5bc9418ae96d5 to your computer and use it in GitHub Desktop.
Save xaxxon/cbca2a4c89b8507231a5bc9418ae96d5 to your computer and use it in GitHub Desktop.
/**
* Creates an object that is never cleaned up by using placement new into a local memory buffer
* Useful for singletons
*/
template<class T>
struct Immortal {
template<class... Args>
Immortal(Args&&... args) {
::new(space) T(std::forward<Args>(args)...);
}
operator T&() & noexcept { return reinterpret_cast<T&>(space); }
private:
alignas(T) unsigned char space[sizeof(T)];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment