0

When I read the source code of Json11, I found something that puzzled me.

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

Why does the function statics return a reference value s that declared as static const?

Why use the function statics to get the member null?

Drise
  • 4,310
  • 5
  • 41
  • 66
ehds
  • 665
  • 1
  • 6
  • 16

1 Answers1

2

The Statics struct, as the comment states, is meant to hold constant values that are used repeatedly across the code. Instead of creating multiple instances of these frequently-used objects, only one is necessary, reducing the memory usage (and maybe making comparison easier). The function statics() returns a reference to a unique, global instance of the Statics struct. This is somewhat like a singleton pattern in C++, although, as NathanOliver pointed out, Statics still has a public constructor, so there is nothing stopping you from creating new instances of the struct.

The constructor of Json uses the kind-of-singleton Statics instance to get it's null member, which is a pointer to a JsonNull object. This means that every new Json object is created with null value, but the same instance of JsonNull is used to initialize all of them. Since both the Statics object and its members are const, there is (in principle) no possibility of modifying the static data by accident.

jdehesa
  • 58,456
  • 7
  • 77
  • 121