关于 Json11 源代码的一些困惑
Some confusions about source code of Json11
当我阅读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
的,因此(原则上)不可能意外修改静态数据。
相关文章:
- 在Linux中哪里可以找到互斥、未来等的源代码
- 如果编译的源代码是特定于它编译的硬件的,我们如何分发它
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 难以理解某些人解决IOI问题的源代码
- 使用g++编译hdf5源代码
- 如何使用C++读取另一个程序中的源代码输出
- Poco FindMySql.cmake 无法找到 MySQL 源代码
- 更改命令行 qt5 源代码构建配置的正确/快速方法
- C++出现控制台错误.我无法识别源代码的问题
- Qt Quick,如何更改 Ui 源代码?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 从macOS Catalina上的源代码编译LLVM(如何解决未找到"stdio.h")
- 如何使用QT创建器获取网页源代码?
- 从源代码构建 gRPC C++
- 如何使用我构建的库,而不会从源代码出错,但不为我自己的项目编译?
- 如何在使用 LLVM 编译时获取部分源代码的二进制代码
- 如何在源代码中包含外部库的头文件?
- 如何查找 torch.bmm 的 c++ 源代码 pytorch.
- 是否有可能使用debug_info获取ELF文件的源代码?
- 关于 Json11 源代码的一些困惑