关于 Json11 源代码的一些困惑

Some confusions about source code of Json11

本文关键字:Json11 源代码 关于      更新时间:2023-10-16

当我阅读Json11的源代码时,我发现了一些让我困惑的东西。

/* * * * * * * * * * * * * * * * * * * *
* Static globals - static-init-safe
*/
struct Statics {
const std::shared_ptr<JsonValue> null = make_shared<JsonNull>();
const std::shared_ptr<JsonValue> t = make_shared<JsonBoolean>(true);
const std::shared_ptr<JsonValue> f = make_shared<JsonBoolean>(false);
const string empty_string;
const vector<Json> empty_vector;
const map<string, Json> empty_map;
Statics() {}
};
static const Statics & statics() {
static const Statics s {};
return s;
}
/* * * * * * * * * * * * * * * * * * * *
* Constructors
*/
Json::Json() noexcept                  : m_ptr(statics().null) {}
Json::Json(std::nullptr_t) noexcept    : m_ptr(statics().null) {}

为什么函数statics返回声明为静态常量s参考值?

为什么使用函数statics获取成员 null?

如注释所述,Statics结构旨在保存跨代码重复使用的常量值。无需创建这些常用对象的多个实例,只需要一个实例,从而减少了内存使用量(并且可能使比较更容易)。函数statics()返回对Statics结构的唯一全局实例的引用。这有点像 C++ 中的单例模式,尽管正如 NathanOliver 指出的那样,Statics仍然有一个公共构造函数,因此没有什么可以阻止您创建结构体的新实例。

Json的构造函数使用单例Statics实例的种类来获取其null成员,该成员是指向JsonNull对象的指针。这意味着每个新的Json对象都是使用 null 值创建的,但使用相同的JsonNull实例来初始化所有这些对象。由于Statics对象及其成员都是const的,因此(原则上)不可能意外修改静态数据。