Moving to Modern C++
C++11 and C++14 big-name features
auto , smart pointers, move semantics, lambdas, concurrency
- braces vs parentheses of object creation
- alias declaration vs typedefs
- constexpr vs const
- const member functions and thread safety
Item7: Distingushes between () and {} when creating objects
- initializer
int x(0);
int x = 0;
int x{0};
int x = {0};
- User defined types
Widget w1; // call default contructor
Widget w2 = w1; // not an assginment; calls copy constructor
w1 = w2; // an assignment; calls copy operator=
- uniform initialization
- braced initialization
std::vector<int> v{ 1, 3, 5 };
A novel feature of braced initialization is that it prohibits implicit narrowing
conversion among built-in types
- most vexing parse
The drawback to braced initialization is the some-times surprising behavior that accompanies it.
The more you like auto, the less enthusiastic you’re likely to be about braced initialization.
narrowing conversions are prohibited inside braced initializers
Only if rhere’s no way to convert the types of arguments in a braced initializer to the type in a std::initializer do compilers fall back on normal overload resolution
- braced initializers, std::initializer_lists, constructor overloading
whether use parentheses or braces? The author can’t know. Only the caller know.
Things to Remeber
- Braced initialization is the most widely usable initialization syntax, it prevents narrowing conversions, and it’s immune to C++’s most vexing parse
- Choosing between parentheses and braces for object creation inside templates can be challenging
Item8: Prefer nullptr to 0 and NULL
C++98 programmers should avoid overloading on pointer and integral types
nullptr’s advantage is that it doesn’t have an integral type
Things to Remember
- Prefer nullptr to 0 and NULL
- Avoid overloading on integral and pointer types
Item9: Prefer alias declarations to typedefs
using UPtrMapSS =
std::unique_ptr<std::unordered_map<std::string, std::string>>:
typedef void (*FP)(int, const std::string&);
// same meaning as above
using FP = void (*)(int, const std::string&);
- alias template
Things to remember
- typedefs don’t support templatization, but alias declarations do
- Alias templates avoid the “::type” suffix and, in templates, the “typename” prefix often required to refer to typedefs
- C++14 offers alais templates for all the C++11 types trails transformations