C++11/C++14 The nullptr and strong typed enumerations- 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
The constant 0 has had the double role of constant integer and null pointer constant. The ambiguity inherent in the double meaning of 0 was dealt with in C by the use of the preprocessor macro NULL, which commonly expands to either ((void*)0) or 0.
C++ didn't adopt the same behavior, allowing only 0 as a null pointer constant.
This interacts poorly with function overloading:
void foo(char *); void foo(int);
If NULL is defined as 0, which function the statement foo(NULL) will call?
Probably, it will call foo(int), which is almost certainly not what the programmer intended. In other words, there is an ambiguity.
So, C++11 corrected this by introducing a new keyword to serve as a distinguished null pointer constant (nullptr):
char *pc = nullptr; // OK int *pi = nullptr; // OK bool b = nullptr; // OK. b is false. int i = nullptr; // error foo(nullptr); // calls foo(char *), not foo(int);
In C++03, enumerations are not type-safe. They are effectively integers, even when the enumeration types are distinct. This allows the comparison between two enum values of different enumeration types.
// C++ 03 enum Day {Sunday, Monday, Tuesday}; enum Month {January, February, March}; Day d = Monday; Month m = February; if (d == m) std::cout << "Monday == February\n"; // This will be printed out else std::cout << "Monday != February\n"; // C++ 11 enum class Day { Sunday, Monday, Tuesday }; enum class Month { January, February, March }; Day d = Day::Monday; Month m = Month::February; // No "==" operator is defined for the object type nor overloaded // So, in C++ 11, this is an compile time error if (d == m) std::cout << "Monday == February\n"; else std::cout << "Monday != February\n";
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