C++ 11
Probably one of the most interesting but biggest evolution of the C++ language.
There is a lot of new (but exciting!) enhancements in C++11.
Table of Contents
Lambda Expressions
Define a function locally, at the place of the call.
Syntax:
[capture](parameters) -> return-type { body }
capture
: list of zero or more captures, either by reference (&
) or by copy (=
). Optionally beginning with capture-defaultcapture-default
&
: auto captures by referencecapture-default
=
: auto captures by copy
Example:
std::vector<int> c = {1, 2, 3, 4, 5, 6, 7};
int x = 5;
c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; }), c.end());
Delegating Constructors
One constructor can call another constructor using constructor (...) : constructor (...)
.
class A {
public:
int a;
A() {}
A(int a) {
a = a;
}
A(int b, int c): A(b*c) {}
};
Default and Delete
Default constructors and destructors can be auto-generated by the compiler with default
keyword.
A class can be made non-copiable by removing the copy constructors with delete
keyword.
class A {
A() = default; // C++11 default constructor
virtual ~A() = default; // C++11 default destructor
A &operator = (const A &) = delete; // C++ way to prevent copy
A (const A &) = delete; // C++ way to prevent copy
};
Uniform Initialization Systems
C++11 provides simplified and unified way to initialize a variable / object.
class A {
int a, b;
public:
A(int i, int j);
};
A a {0,0}; // C++11. Equivalent to: A a(0,0);
int* a = new int[3] { 1, 2, 0 }; // C++11 Array Initialization
class B {
int a[4];
public:
B() : a{1,2,3,4} {} // C++11, member array initializer
};
// C++11 Container Initialization
std::vector<string> days={ "monday", "tuesday", "wednesday"};
nullptr
Existing NULL
macro or 0
for assigning null pointer is both error prone and weakly typed.
A new keyword nullptr
is introduced to assign and check nullpointers with type safety.
Automatic Type Deduction
auto
keyword can be used when the type is deductible:
auto d = 0.5 // double
auto iterator = vec.begin();
decltype
decltype
is a new keyword to capture the type of an object or expression.
const std::vector<int> vec;
typedef decltype (vec.begin()) IT;
IT vec_it;
Rvalue References
C++11 introduces the concept of rvalue references
in order to facilitate the move semantic.
Definitions and types of values:
- lvalue
: Anything that can be on the left side of equal sign.
- xvalue
: An rvalue that about to expire (something being returned from a function, for example). An xvalue can be moved.
- prvalue
: An rvalue that is not about to expire, like a literal (12, true) or the result of a non-reference return of a function.
Example of a movable class taking advantage of rvalues.
class Movable {
Movable (Movable&&); // move constructor
Movable&& operator=(Movable&&); // move assignment
};
Smart pointers
Two new smart pointer classes: shared_ptr
(with reference count) and unique_ptr
(at most one copy).
Smart pointers encapsulate pointers into a safe container, which will guarantee destruction even in the event of an exception.
auto_ptr
is deprecated.
unique_ptr<T> ptr(new T); // Ok
unique_ptr<T> noMovePtr = myPtr; // Error: Can't copy unique_ptr
unique_ptr<T> otherPtr = std::move(ptr); // Ok, resource moved to otherPtr
Threadding Library
Introduce standard multi-threading library with std::thread
, including various threading constructs:
- std::future
: an object storing a value that will be assigned in future, with a blocking get()
accessor.
- std::promise
: associated to a future object, to set its value
- std::thread
: a class representing a lightweight thread
- std::this_thread::get()
: the current thread id
- std::this_thread::sleep_for()
: a sleep function
- std::mutex
: a standard mutex synchronization primitive
Promise example:
std::promise<int> thePromise;
std::future<int> theFuture = thePromise.get_future();
// start another thread which will set the promise
std::thread t(initiazer, &thePromise);
// => thePromise.set_value(48);
std::cout<<theFuture.get()<<std::endl;
t.join();
Variadic templates
To create a function / constructor which takes an unlimited number of arguments of any type.
The parameter expansion happens at compile time - no runtime penalty.
Variadic class template (from cppreference.com):
template<class... Types> struct Tuple {};
Tuple<> t0; // Types contains no arguments
Tuple<int> t1; // Types contains one argument: int
Tuple<int, float> t2; // Types contains two arguments: int and float
Tuple<0> t3; // error: 0 is not a type
Variadic function template (from cppreference.com):
template<class... Types> struct Tuple {};
Tuple<> t0; // Types contains no arguments
Tuple<int> t1; // Types contains one argument: int
Tuple<int, float> t2; // Types contains two arguments: int and float
Tuple<0> t3; // error: 0 is not a type
Move semantics
C++11 introduces a big shift with move semantics, allowing the compiler to move a returned object instead of copying it.
It has two advantages: 1. It allows to turn expensive copies into cheap moves, e.g. when returning objects from functions 2. It allows to implement “move-only” semantic, where some objects cannot be copied but only moved (e.g. unique_ptr)
Algorithms
A collection of new set oriented functions:
all_of(It first, It last, UnaryPredicate p)
: check if predicate returns true for all elementsany_of(It first, It last, UnaryPredicate p)
: check if predicate returns true for at least one elementnone_of(It first, It last, UnaryPredicate p)
: check if predicate returns true for no element
New stdlib features
std::move
: transfer the resources of the object passed (e.g. transferunique_ptr
).std::forward
: used to transfer parameters as is to other functions, maintaining value category (lvalue/rvalue) and const qualifier.std::thread
: a new threading library for C++.std::to_string
: converts numeric arguments to string.std::chrono
: set of utility functions to deal with durations, clocks and time. E.g.std::chrono::steady_clock::now();
.std::unique_ptr
: a non-copyable, single-owner but movable smart pointer.std::shared_ptr
: smart pointer to manage shared resources in thread-safe way.std::make_shared
: recommended way to build a shared pointer to avoidnew
and with exception safety.std::async
: run function in async (or lazy) context, returning a future.std::array
: a container built on top of traditional C arrays supporting container operations.std::tuple
: fixed size collection of heterogeneous values, e.g.std::tuple<int, std::string>
.type traits
: query properties of types at compile time, e.g.std::is_integral
,std::is_same
.std::begin
: a free function to get an iterator to the first element of a container.std::end
: a free function to get an iterator to the last element of a container.