1

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.

adrianmcmenamin
  • 1,081
  • 1
  • 15
  • 44
  • 1
    The short answer is that you can read the above line as `HTTPServer* const server_ = nullptr;` – Ted Lyngmo Jun 09 '20 at 12:59
  • Thanks, didn't know about that short version. – Zer0Knowledge Jun 09 '20 at 13:01
  • 1
    You're welcome! The above does look a bit strange though. Since the pointer is `const` and initialized to `nullptr` it will not be possible to change it to point at a `HTTPServer` instance later. – Ted Lyngmo Jun 09 '20 at 13:04
  • There is a constructor which can be used to intialize it to something else. This way it makes sense. – Zer0Knowledge Jun 09 '20 at 13:14
  • That would be applicable if an `HTTPServer` was instantiated. I don't see that happening here. It's initializing the pointer no matter if `HTTPServer` has a constructor that accepts a `nullptr` or not. – Ted Lyngmo Jun 09 '20 at 13:21
  • No, I mean that the class having the pointer to HTTPServer as a class member has a constructor initializing it. – Zer0Knowledge Jun 09 '20 at 14:59
  • Aha, yes, that would work. `class Carrier { Carrier() : server_(new HTTPServer) {} ...` would override the default initialization. – Ted Lyngmo Jun 09 '20 at 15:08

1 Answers1

3

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.

whiskeyo
  • 873
  • 1
  • 9
  • 19