c++namingfolly

Curly braces in variable names


Lately I've been browsing through some code of facebooks folly library and saw a variable named like

HTTPServer* const server_{nullptr};

as a class member. I've never seen something like this before and wondered if there is any special meaning. Googling only made me found other examples like this one in boost code to.

Maybe someone has an explanation.


Solution

  • It is used as an initializer list. In your case, HTTPServer pointer would be set to nullptr, but you can use curly braces even with plain types such as int, float, etc.

    Its role is to initialize the variable with value(s) inside, which means that both attitudes below mean the same:

    int x = 10; 
    int x{10};
    

    You can also initialize arrays in much simpler way:

    int x[5] = { 1, 2, 3, 4, 5 };
    

    instead of using:

    x[0] = 1;
    x[1] = 2;
    x[2] = 3;
    x[3] = 4;
    x[4] = 5;
    

    If you wish, you can also use

    int x{};
    

    to initialize x with the value of 0.