Initializers

Uniform initialization syntax may be the most needed and welcome change to the C++ language. Unfortunately, I fear that it will be difficult to encourage adoption, and even more so, I doubt that we will see a huge push to retrofit old code no matter how badly it may need the fix.

The following is an example of an array/vector initialization from some code I wrote for our LexĂ­meter product. I have removed the typedefs from the code which unfortunately makes it a little uglier than it is in practice. And I have deleted and added a few lines to make it suitable for a standalone demonstration, as well as reformatting the lines to make them fit the screen. Call that the "standard disclaimer."

1 #define NUMELEMENTS(x) (sizeof(x)/sizeof(*x))
2 using namespace std;
3 static const string strParams[] = 
4 {
5   string("docs"),
6   string("method"),
7   string("type")
8 };  
9 static vector<string> requiredParams(strParams, strParams+NUMELEMENTS(strParams));

The intent of all this mumbo-jumbo is to create a const standard vector of standard strings, and initialize the members just once with the literals docs, method, and type.

The new initialization syntax will allow me to replace the duplication (storing the literals in an array so that I can move them to a vector) and the code that moves things around in line 9 using the vector's constructor --- a constructor that half the C++ programmers do not understand when they see it. The replacement code is shown below:

static vector<string> requiredParams{"docs", "method", "type"};

That thing in the braces is called an initializer_list, or more correctly, a std::initializer_list. And through the grace of the Madrid committee, we can use it everywhere we used any previously existing initialization syntax:

OLD:
  int i = 0;
  int j(0);
NEW:
  int i{0};
  int j{0};

Neither of those examples is terribly confusing, and the old syntax is still legal, and will remain legal. It does not appear that C++11 is headed down the road charted by Fortran 66, 77, and later with deprecated features, although the new syntax is designed to supersede the old.

 

Last updated 2014-07-19T15:44:11+00:00.

Links to the standard

This is a big topic, and the information is spread around the standard. The initializer_list topic is in 18.9, and is probably the place to start. There is also a good discussion in Stroustrup's slides for the Madrid conference, starting with slide #74. You can download the slides.

Benefits

At long last there is a single syntax that can be used everywhere. It is unambiguous, at least if you are comparing it to the crazy mix of function-like syntax we have grown used to.

Risks

This is truly new syntax, and adoption will be slow even after the feature is widely available in the compilers.