gpt4 book ai didi

c++ - Json11源码的一些困惑

转载 作者:行者123 更新时间:2023-11-28 01:35:39 25 4
gpt4 key购买 nike

在阅读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 返回一个声明为 static const 的引用值 s

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

最佳答案

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

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

关于c++ - Json11源码的一些困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49365855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com