C++11/C++14 initializer_list - 2020
"If you're an experienced C++ programmer and are anything like me, you initially
approached C++11 thinking, "Yes, yes, I get it. It's C++, only more so." But as you
learned more, you were surprised by the scope of the changes. auto declarations,
range-based for loops, lambda expressions, and rvalue references change the face of
C++, to say nothing of the new concurrency features. And then there are the
idiomatic changes. 0 and typedefs are out, nullptr and alias declarations are in.
Enums should now be scoped. Smart pointers are now preferable to built-in ones.
Moving objects is normally better than copying them.
- Effective Modern C++ by Scott Meyers
When we want to initialize a vector, we had to do the following:
// C++03 std::vectorv; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4);
Now, with C++ 11, we can do this:
// C++11 std::vectorv = { 1, 2, 3, 4 };
C++11 binds the concept to a template, called std::initializer_list. This allows constructors and other functions to take initializer-lists as parameters:
#include <iostream> #include <vector> class MyNumber { public: MyNumber(const std::initializer_list<int> &v;) { for (auto itm : v) { mVec.push_back(itm); } } void print() { for (auto itm : mVec) { std::cout << itm << " "; } } private: std::vector<int> mVec; }; int main() { MyNumber m = { 1, 2, 3, 4 }; m.print(); // 1 2 3 4 return 0; }
C++11/C++14 New Features
initializer_list
Uniform initialization
Type Inference (auto) and Range-based for loop
The nullptr and strongly typed enumerations
Static assertions and Constructor delegation
override and final
default and delete specifier
constexpr and string literals
Lambda functions and expressions
std::array container
Rvalue and Lvalue (from C++11 Thread tutorial)
Move semantics and Rvalue Reference (from C++11 Thread tutorial)
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization