鍍金池/ 問(wèn)答/C++/ 閱讀Json11源碼的疑惑,關(guān)于靜態(tài)局部常量?

閱讀Json11源碼的疑惑,關(guān)于靜態(tài)局部常量?

本著學(xué)習(xí)的態(tài)度,決定閱讀一下Json11的源碼,再有一處發(fā)現(xiàn)如下代碼.

/* * * * * * * * * * * * * * * * * * * *
* 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() {}
};

//這個(gè)函數(shù)的作用感覺(jué)比較模糊,在函數(shù)內(nèi)部定義了一個(gè)靜態(tài)常量并且返回其引用
static const Statics & statics() {
static const Statics s {};
return s;
}

.........
//在Json類的構(gòu)造函數(shù)中對(duì)于空值的初始化使用了 statics().null
//請(qǐng)問(wèn)這樣做的原由是什么?
Json::Json() noexcept                  : m_ptr(statics().null) {}
Json::Json(std::nullptr_t) noexcept    : m_ptr(statics().null) {}

疑惑一:statics()為什么要返回常量引用? 避免更改和復(fù)制操作?

疑惑二:內(nèi)部為什么要申明為static const類型?s只會(huì)被初始化一次?

回答
編輯回答
兔囡囡

答一:
靜態(tài)變量引用C++11 單例的一種寫法,這里常量的作用主要是為了避免更改 empty_string,empty_vector,empty_map。

答二:
是的,靜態(tài)變量引用C++11 單例的一種寫法。常量的意義見答一。

2018年9月8日 03:46