Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions include/singleton.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,7 @@ struct Singleton
Instance(const Instance&) = delete;
~Instance()
{
// Destroys the locally-initialized instance. Injected ones are ignored (no ownership).
if (m_pExtern == LOCAL_INSTANCE_ID)
GetBuffer().~T();
DestroyLocalInstance();
}
Instance& operator =(const Instance&) = delete;
/// Returns the current instance.
Expand All @@ -91,7 +89,7 @@ struct Singleton
template <typename ...Args>
void Emplace(Args&&... args)
{
this->~Instance();
DestroyLocalInstance();
try
{
new (&GetBuffer()) T(std::forward<Args>(args)...);
Expand All @@ -108,7 +106,7 @@ struct Singleton
*/
void SetExtern(T* ptr)
{
this->~Instance();
DestroyLocalInstance();
m_pExtern = ptr;
}
private:
Expand All @@ -123,6 +121,13 @@ struct Singleton
// Static, uninitialized buffer for the singleton's object
static union U { T asT; U(){} ~U(){} } buffer;
return buffer.asT;
}
/// Destroys the local instance, while ignoring injected ones (no ownership).
/** @remark This leaves the object in an inconsistent state. m_pExtern must be changed. */
void DestroyLocalInstance()
{
if (m_pExtern == LOCAL_INSTANCE_ID)
GetBuffer().~T();
}
} g_instance;

Expand Down