Skip to content
This repository has been archived by the owner on Mar 26, 2020. It is now read-only.

Remove invoking of the non-trivial destructor. #128

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
45 changes: 41 additions & 4 deletions json11.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
#include <cstdlib>
#include <cstdio>
#include <limits>
#include <new>
#include <utility>

namespace json11 {

Expand All @@ -46,6 +48,41 @@ struct NullStruct {
bool operator<(NullStruct) const { return false; }
};

/* NoDestructor
*
* Wrapper that makes it easy to create an object of type T with static storage duration that:
* - is only constructed on first access
* - never invokes the destructor
*/
template <typename T>
class NoDestructor {
public:
template <typename... Args>
explicit NoDestructor(Args&&... args) {
new (storage_) T(std::forward<Args>(args)...);
}

explicit NoDestructor(const T& x) { new (storage_) T(x); }
explicit NoDestructor(T&& x) { new (storage_) T(std::move(x)); }

NoDestructor(const NoDestructor&) = delete;
NoDestructor& operator=(const NoDestructor&) = delete;

~NoDestructor() = default;

const T& operator*() const { return *get(); }
T& operator*() { return *get(); }

const T* operator->() const { return get(); }
T* operator->() { return get(); }

const T* get() const { return reinterpret_cast<const T*>(storage_); }
T* get() { return reinterpret_cast<T*>(storage_); }

private:
alignas(T) char storage_[sizeof(T)];
};

/* * * * * * * * * * * * * * * * * * * *
* Serialization
*/
Expand Down Expand Up @@ -236,14 +273,14 @@ struct Statics {
};

static const Statics & statics() {
static const Statics s {};
return s;
static const NoDestructor<Statics> s;
return *s;
}

static const Json & static_null() {
// This has to be separate, not in Statics, because Json() accesses statics().null.
static const Json json_null;
return json_null;
static const NoDestructor<Json> json_null;
return *json_null;
}

/* * * * * * * * * * * * * * * * * * * *
Expand Down