Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand meaning of {...} when creating objects

Tags:

c++

c++11

I came across the following code

#include <iterator>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>

int main() {

    std::string inputfilename, outputfilename;

    std::cin  >> outputfilename;

    std::ofstream outputfile{ outputfilename };

    outputfile << "I exist Yo!";

    return 0;
}

My first reaction was that it should not compile. I had never seen the outputfile{ outputfilename }; syntax. Can someone please tell me what feature of the C++ language defines the behavior of {...} in this line of code?

P.S. The code works and does what you would expect.

like image 411
The Vivandiere Avatar asked Feb 10 '23 18:02

The Vivandiere


1 Answers

From the C++11 Standard (emphasis mine):

8.5.4 List-initialization [dcl.init.list]

1 List-initialization is initialization of an object or reference from a braced-init-list. Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list. An initializer list may be empty. List-initialization can occur in direct-initialization or copy-initialization contexts; list-initialization in a direct-initialization context is called direct-list-initialization and list-initialization in a copy-initialization context is called copy-list-initialization. [ Note: List-initialization can be used

  • as the initializer in a variable definition (8.5)
  • as the initializer in a new expression (5.3.4)
  • in a return statement (6.6.3)
  • as a function argument (5.2.2)
  • as a subscript (5.2.1)
  • as an argument to a constructor invocation (8.5, 5.2.3)
  • [..]
like image 187
R Sahu Avatar answered Feb 21 '23 12:02

R Sahu