C++11/C++14 default and delete specifiers- 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
If a class is defined with any constructors, the compiler will not generate a default constructor. This is useful in many cases, but it is some times vexing. For example, we defined the class as below:
class A { public: A(int a){}; };
Then, if we do:
A a;
The compiler complains that we have no default constructor. That's because compiler did not make the one for us because we've already had one that we defined.
We can force the compiler make the one for us by using default specifier:class A { public: A(int a){} A() = default; };
Then, compiler won't complain for this any more:
A a;
Suppose we have a class with a constructor taking an integer:
class A { public: A(int a){}; };
Then, the following three operations will be successful:
A a(10); // OK A b(3.14); // OK 3.14 will be converted to 3 a = b; // OK We have a compiler generated assignment operator
However, what if that was not we wanted. We do not want the constructor allow double type parameter nor the assignment to work.
C++11 allows us to disable certain features by using delete:
class A { public: A(int a){}; A(double) = delete; // conversion disabled A& operator=(const A&) = delete; // assignment operator disabled };
Then, if we write the code as below:
A a(10); // OK A b(3.14); // Error: conversion from double to int disabled a = b; // Error: assignment operator disabled
In that way, we could achieve what we intended.
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