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.