SlideShare a Scribd company logo
Usability enhancements Type deduction Move semantics Lambda expressions
Modern C++ (C++11/14)
Geeks Anonymes
Damien Gerard
October 19th, 2016
Usability enhancements Type deduction Move semantics Lambda expressions
Introduction
“C++11 feels like a new language.” Bjarne Stroustrup (inventor of C++)
Usability enhancements Type deduction Move semantics Lambda expressions
Labels
11 since C++11
14 since C++14
17 since C++17
R that ain’t for kids
Usability enhancements Type deduction Move semantics Lambda expressions
Range-based for loop
for statement syntax extended to allow for easy iteration over a range of
elements:
int myArray[5] = {1, 2, 3, 4, 5};
for(int x : myArray) {
std::cout << x << std::endl;
}
for(int& x : myArray) {
x *= 2; // double value and save
}
for(auto& x : myArray) { // auto = int
x *= 2;
}
11

Recommended for you

Effective Modern C++
Effective Modern C++Effective Modern C++
Effective Modern C++

The document discusses various aspects of template type deduction in C++ including: 1. How the type T and the type of the parameter ParamType are deduced based on whether ParamType is a pointer/reference, universal reference, or neither. 2. How array arguments are handled differently when passed by value versus by reference in templates. 3. How function arguments are treated, with function types decaying to function pointers. 4. The differences between auto type deduction and template type deduction. 5. How decltype can be used to deduce types from expressions while preserving reference-ness.

c++11c++14effective
Toolchain
ToolchainToolchain
Toolchain

The document discusses toolchains and cross toolchains. It defines a toolchain as a collection of tools including a C compiler, C libraries, and binary utilities. A cross toolchain is a toolchain configured to compile code for a platform other than the one on which the toolchain is running. The document outlines steps for building a cross toolchain, including obtaining kernel headers, building binary utilities, compilers, and libraries. It also discusses automated build tools like Crosstool and testing the generated cross toolchain.

crosstoolchainembedded linux
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency

The document is a tutorial on C++11 concurrency features such as asynchronous tasks, threads, promises, mutexes, and condition variables. It covers topics like spawning asynchronous tasks using std::async and std::thread, returning values from asynchronous tasks, passing parameters, handling exceptions, manually setting futures using std::promise and std::packaged_task, waiting for multiple futures, and using mutexes and lock guard templates for synchronization. Code examples are provided to illustrate the various concurrency features.

c++ 11cpncurrency program
Usability enhancements Type deduction Move semantics Lambda expressions
auto
Constant iterator over a vector:
std::vector<int> vec(4,100); // four ints with value 100
for(std::vector<int>::const_iterator it = vec.cbegin();
it != vec.cend(); ++it)
{
std::cout << *it << std::endl;
}
auto for type deduction:
std::vector<int> vec(4,100); // four ints with value 100
for(auto it = vec.cbegin(); it != vec.cend(); ++it) {
std::cout << *it << std::endl;
}
11
Usability enhancements Type deduction Move semantics Lambda expressions
Null pointer literal
Constant 0 had the double role of constant integer and null pointer
constant.
void f(int*);
void f(int);
f(NULL); // calls f(int) or error: ambiguous
If NULL defined as 0, f(NULL) calls f(int). Most programmers would
expect f(int*) because NULL means a null pointer in their mind.
Usability enhancements Type deduction Move semantics Lambda expressions
Null pointer literal
nullptr is a pointer literal of type nullptr_t, which is implicitly
convertible and comparable to any pointer type. It is not implicitly
convertible or comparable to integral types, except for bool.
char* pc = nullptr; // compiles
int* pi = nullptr; // compiles
bool b = nullptr; // compiles, b is false
int i = nullptr; // error
f(nullptr); // calls f(int*), not f(int)
f(nullptr_t) will actually call f(int*) using implicit conversion.
11
Usability enhancements Type deduction Move semantics Lambda expressions
Initializer lists
C++03 inherited the initializer-list feature from C.
struct Widget {
float first;
int second;
};
Widget w1 = {0.43f, 10}; // first=0.43f and second=10
Widget w2[] = {{13.4f, 3}, {43.2f, 29}};
Useful albeit limited to Plain Old Data (POD) structs and classes.

Recommended for you

Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE

Programming in C Presentation upto FILE Facebook >> facebook.com/diptasaha.lpu.cse Email >> diptasaha.lpu.cse@gmail.com

Linux Ethernet device driver
Linux Ethernet device driverLinux Ethernet device driver
Linux Ethernet device driver

The document discusses Ethernet device drivers in Linux. It describes the driver architecture, Ethernet packet format, driver development process, and important data structures like net_device and sk_buff. It provides examples of initializing a driver, probing hardware, uploading/downloading data using callbacks, interrupt handling, and buffer management. The key steps are registering the driver, allocating network devices, setting callbacks, and using sk_buff objects to transfer packets between layers.

niclinuxdevice driver
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++

The document discusses various string handling, mathematical, and random number generation functions available in C++ library. It provides examples of functions like strlen(), strcpy(), strcmp(), sqrt(), pow(), randomize(), random(). It also provides programs to demonstrate the use of these functions for tasks like checking palindromes, searching strings, toggling case, generating random numbers in a given range.

libraryfunctionssqrt
Usability enhancements Type deduction Move semantics Lambda expressions
Uniform initialization
Initializer-lists for all classes, including standard containers.
std::vector<std::string> v = { "Hello", "world" };
std::vector<std::string> v({ "Hello", "world" });
std::vector<std::string> v{ "Hello", "world" };
int val = 5.2; // automatic narrowing
int val{5.2}; // error or warning: type ’double’
// cannot be narrowed to ’int’ in initializer list
// insert an explicit static cast static_cast<int>( )
Widget getWidget() {
return {0.43f, 10}; // no need for explicit type
}
11
Usability enhancements Type deduction Move semantics Lambda expressions
Most vexing parse
struct Widget {
Widget();
};
struct WidgetKeeper {
WidgetKeeper(Widget w);
};
WidgetKeeper wKeeper(Widget()); // most vexing parse
Ambiguous call:
1 new instance of Widget, sent to constructor of WidgetKeeper;
2 function declaration: name“wKeeper”, return type WidgetKeeper,
single (unnamed) parameter which is a function returning type
Widget.
Usability enhancements Type deduction Move semantics Lambda expressions
Most vexing parse
Most developers expect the first, but the C++ standard requires it to be
interpreted as the second.
Workaround in C++03 to ensure the first interpretation:
WidgetKeeper time_keeper( (Widget()) );
C++11’s uniform initialization syntax:
WidgetKeeper time_keeper{Widget{}}; 11
Usability enhancements Type deduction Move semantics Lambda expressions
Returning multiple values
void divide(int dividend, int divisor, int& quotient,
int& remainder)
{
quotient = dividend / divisor;
remainder = dividend % divisor;
}
Or even worse, return quotient through the returned value and
remainder as a reference variable:
int divide(int dividend, int divisor, int& remainder) {
remainder = dividend % divisor;
return dividend / divisor;
}

Recommended for you

Modern C++
Modern C++Modern C++
Modern C++

Utah Code Camp, Spring 2016. http://utahcodecamp.com In this presentation I describe modern C++. Modern C++ assumes features introduced in the C++11/14 standard. An overview of the new features is presented and some idioms for mdoern C++ based on those features are presented.

c++software developmentutah code camp
Loops in c
Loops in cLoops in c
Loops in c

The document discusses different types of loops in C programming: for loops, while loops, and do-while loops. For loops allow initialization of a variable, specify a condition, and how to increment the variable. While loops repeatedly execute code as long as a condition is true. Do-while loops are similar but check the condition at the bottom of the loop, so the code executes at least once. Examples of each loop type are provided.

baabtra mentoring partner
Embedded linux network device driver development
Embedded linux network device driver developmentEmbedded linux network device driver development
Embedded linux network device driver development

The document discusses developing network device drivers for embedded Linux. It covers key topics like socket buffers, network devices, communicating with network protocols and PHYs, buffer management, and differences between Ethernet and WiFi drivers. The outline lists these topics and others like throughput and considerations. Prerequisites include C skills, Linux knowledge, and an understanding of networking and embedded driver development.

embeddedlinuxdrivers
Usability enhancements Type deduction Move semantics Lambda expressions
Returning multiple values
Or, but rather heavy:
struct divideResult {
int quotient;
int remainder;
};
divideResult divide(int dividend, int divisor) {
return { dividend / divisor, dividend % divisor };
}
divideResult result = divide(10, 3);
std::cout << result.quotient << std::endl;
std::cout << result.remainder << std::endl;
11
Usability enhancements Type deduction Move semantics Lambda expressions
Returning multiple values
std::tuple<int,int> divide(int dividend, int divisor) {
return std::make_tuple(dividend / divisor,
dividend % divisor);
}
int quotient, remainder;
std::tie(quotient, remainder) = divide(10, 3);
C++17’s structured bindings (Clang-4.0 only, as of today):
auto [quotient, remainder] = divide(10, 3);
std::cout << quotient << std::endl;
std::cout << remainder << std::endl;
11
17
Usability enhancements Type deduction Move semantics Lambda expressions
std::unordered *
std::set, map, multiset, multimap associative containers are
implemented as balanced trees. The std::unordered_set,
unordered_map, unordered_multiset, unordered_multimap
alternatives are implemented as hash tables.
Including hash tables was one of the most recurring requests. It was not
adopted in C++03 due to time constraints only. Although hash tables are
less efficient than a balanced tree in the worst case (in the presence of
many collisions), they perform better in many real applications.
11
Usability enhancements Type deduction Move semantics Lambda expressions
emplace, emplace back
emplace and emplace_back can construct an element in-place.
auto employees = std::unordered_map<int, std::string>{};
auto e1 = std::pair<int, std::string>{1, "John Smith"};
employees.insert(e1);
employees.insert(std::make_pair(2, "Mary Jones"));
employees.emplace(3, "James Brown"); // construct in-place
for (const auto& e : employees) {
std::cout << e.first << ": " << e.second << std::endl;
}
11

Recommended for you

Exception handling
Exception handlingException handling
Exception handling

Exceptions are runtime errors that a program may encounter. There are two types: synchronous from faults in input data, and asynchronous from external events. Exception handling uses try, throw, and catch keywords. Code that may cause exceptions is placed in a try block. When an exception occurs it is thrown, and the catch block handles it to prevent program termination. Multiple catch blocks can handle different exception types, and a catch-all block uses ellipses to catch any exception.

c++oopsexception handling
Advanced C - Part 1
Advanced C - Part 1 Advanced C - Part 1
Advanced C - Part 1

C has been the most commonly used language. This slideshare is all about the introduction to Advanced C. You will learn the fundamentals and the problem solving skills. You will also get an idea on building algorithms and the conditions regarding it. There are also slides which will give knowledge about operators and their types. As a whole you will gain knowledge on three important fundamentals of C.

c programmingadvancedcembedded systems
Clanguage
ClanguageClanguage
Clanguage

- C is a commonly used language for embedded systems that is portable, produces efficient code, and uses a fairly concise syntax. - It was developed in the late 1960s and early 1970s and was influenced by the B programming language. - C uses basic data types, functions, expressions, statements, and other constructs to provide powerful yet flexible programming capabilities while using relatively little memory.

c++languagevidyacenter.com
Usability enhancements Type deduction Move semantics Lambda expressions
In-class initialization
In C++03, in-class initialization on static const members of integral or
enumeration type only.
struct Widget {
static const int a = 7; // compiles
float b = 7.2; // error: not static const integral
const int c = 7; // error: not static
static int d = 7; // error: not const
static const float e = 7.2; // error: not integral
const static int arr[] = { 1, 2, 3 };
// error: must be initialized out of line
};
Usability enhancements Type deduction Move semantics Lambda expressions
In-class initialization
C++11 allows some of them:
struct Widget {
static const int a = 7;
float b = 7.2;
const int c = 7;
static int d = 7; // still fails
static float e = 7.2; // still fails
constexpr static int arr[] = { 1, 2, 3 };
constexpr static std::complex<double> f = { 1, 2 };
};
A non-const static variable still has to be initialized outside the class with
int Widget::d = 7;
float Widget::e = 7.2;
11
Usability enhancements Type deduction Move semantics Lambda expressions
ODR-use
An object is odr-used if its address is taken, or a reference is bound to it.
If a const or constexpr static data member is odr-used, a redefinition (no
initializer permitted) at namespace scope is required.
struct Widget {
static const int n = 1;
static constexpr int m = 4;
};
const int& f(const int& r);
// call f(Widget::n) or f(Widget::m) somewhere
// redefinition at namespace scope required:
const int Widget::n, Widget::m;
C++17 alleviates this constraint for constexpr. A static data member
declared constexpr is implicitly inline and needs not be redeclared at
namespace scope.
R
11
17
Usability enhancements Type deduction Move semantics Lambda expressions
constexpr
Declare something that can be evaluated down to a constant:
constexpr double pi() { return std::atan(1) * 4; }
constexpr double getCircleSurface(double r) {
return pi() * r * r;
}
const double circleSurface = getCircleSurface(0.5);
or
const float oneEighty = degreesToRadians(180.0f);
Since C++14, constexpr functions may have more than one line.
11
14

Recommended for you

Inline function
Inline functionInline function
Inline function

The document discusses inline functions in C++. Inline functions allow code from a function to be pasted directly into the call site rather than executing a function call. This avoids overhead from calling and returning from functions. Good candidates for inline are small, simple functions called frequently. The document provides an example of a function defined with the inline keyword and the optimizations a compiler may perform after inlining. It also compares inline functions to macros and discusses where inline functions are best used.

C++11
C++11C++11
C++11

C++11 introduced several new features for functions and lambdas including: 1. Lambda expressions that allow the definition of anonymous inline functions. 2. The std::function wrapper that allows functions and lambdas to be used interchangeably. 3. std::bind that binds arguments to function parameters for creating function objects. These features improved support for functional programming patterns in C++.

c++11c++amcbridge
Unix v6 Internals
Unix v6 InternalsUnix v6 Internals
Unix v6 Internals

UNIX v6 Internals: Background knowledge, C programming language, system call, interrupt/trap, PDP-11, scheduler / timer, etc.

v6kernelmultics
Usability enhancements Type deduction Move semantics Lambda expressions
Call other constructors
In C++03, other constructors could not be called. Workaround: call a
common member function
class Widget {
int number_;
void construct(int number) { number_ = number; }
public:
Widget(int number) { construct(number); }
Widget() { construct(42); }
};
Usability enhancements Type deduction Move semantics Lambda expressions
Call other constructors
Wrong workaround:
class Widget {
int number_;
public:
Widget(int number) : number_(number) { }
Widget() {
Widget(42);
// this->number_ = 0 or something undefined
}
};
What is wanted but does not compile:
Widget() : Widget(42) { }
Usability enhancements Type deduction Move semantics Lambda expressions
Call other constructors
In C++11 other peer constructors may be called (“delegation”).
class Widget {
int number_;
public:
Widget(int number) : number_(number) { }
Widget() : Widget(42) { }
};
An object is constructed once any constructor finishes execution. Since
multiple constructors are allowed to execute, each delegating constructor
will be executing on a fully constructed object of its own type.
11
Usability enhancements Type deduction Move semantics Lambda expressions
Call or import base class constructors
Call base class constructor:
struct Base {
Base(int number);
};
struct Derived : Base {
Derived(int number) : Base(number) { }
};
Import all base class constructors:
struct Derived : Base {
using Base::Base
};
// can call Derived(42);
11

Recommended for you

Q2.12: Debugging with GDB
Q2.12: Debugging with GDBQ2.12: Debugging with GDB
Q2.12: Debugging with GDB

GDB can debug programs by running them under its control. It allows inspecting and modifying program state through breakpoints, watchpoints, and examining variables and memory. GDB supports debugging optimized code, multi-threaded programs, and performing tasks like stepping, continuing, and backtracing through the call stack. It can also automate debugging through commands, scripts, and breakpoint actions.

q22012ulrich weigand
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01

Here is a C program to produce a spiral array as described in the task: #include <stdio.h> int main() { int n = 5; int arr[n][n]; int num = 1; int rowBegin = 0; int rowEnd = n-1; int colBegin = 0; int colEnd = n-1; while(rowBegin <= rowEnd && colBegin <= colEnd) { // Top row for(int i=colBegin; i<=colEnd; i++) { arr[rowBegin][i] = num++; } rowBegin++; // Right column for(int i=rowBegin;

languagesc programming
Web I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolWeb I - 05 - HTTP Protocol
Web I - 05 - HTTP Protocol

Lecture on HTTP for Web Development 1 Course suitable for degree following CIT/CIS/CS ACM model curriculum.

teachhttpweb
Usability enhancements Type deduction Move semantics Lambda expressions
Override a base class method
struct Animal {
char* say() const { return "??"; }
};
struct Cow : Animal {
char* say() const { return "moo"; }
};
struct Pig : Animal {
char* say() const { return "oink"; }
};
std::vector<Animal*> animals{new Cow, new Pig};
for(const Animal* a : animals) {
std::cout << a->say() << std::endl;
}
Prints“??” for both the cow and the pig.
Usability enhancements Type deduction Move semantics Lambda expressions
Dynamic polymorphism
struct Animal {
virtual char* say() const { return "??"; }
};
struct Cow : Animal {
virtual char* say() const { return "moo"; }
};
struct Pig : Animal {
virtual char* say() const { return "oink"; }
};
Prints“moo”and“oink”. What if const is forgotten in the Pig’s say()? It
will compile and print“moo”and“??”.
Usability enhancements Type deduction Move semantics Lambda expressions
Typo in derived class
The following code compiles but contains no virtual function overrides.
struct Base {
void f1() const;
virtual void f2() const;
virtual void f3(int x);
}
struct Derived : Base {
void f1() const;
virtual void f2();
virtual void f3(unsigned int x);
}
Usability enhancements Type deduction Move semantics Lambda expressions
overrides
Make explicit that a derived class is expected to override a base class:
struct Derived : Base {
void f1() const override;
virtual void f2() override;
virtual void f3(unsigned int x) override;
}
The compiler will complain about all the overriding-related issues.
11

Recommended for you

C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs

C++17 introduced updates to both the C++ language and standard library. For the language, there were around 45 modest proposals that mostly solved frustrations from prior standards. Significant updates to the library included new vocabulary types like std::optional and std::string_view. C++17 also added features like structured bindings, if constexpr, and lambda improvements like constexpr lambdas and capture of *this. The filesystem library was standardized to provide OS-abstraction for file/directory operations.

cpp17meetup
TCP/IP
TCP/IPTCP/IP
TCP/IP

10 Of The Best Books About TCP/IP And Networking 1.Internet Core Protocols: The Definitive Guide: Help for Network Administrators 2.Effective TCP/IP Programming: 44 Tips to Improve Your Network Programs 3.TCP/IP Explained 4.High-Speed Networks TCP/IP and ATM Design Principles 5.TCP/IP: Architecture, Protocols, and Implementation with IPv6 and IP 6.SNMP, SNMPv2, SNMPv3, and RMON 1 and 2 7.SNMP: A Guide to Network Management 8.TCP/IP Network Administration 9.Teach Yourself Tcp/Ip in 14 Days 10.UNIX Network Programming

networkinglocal area network
Bjarne essencegn13
Bjarne essencegn13Bjarne essencegn13
Bjarne essencegn13

The document provides an overview of Bjarne Stroustrup's views on the C++ programming language. Some key points: 1) C++ aims to provide performance, predictability, teachability, and readability while supporting systems programming, embedded systems, large systems, and both experts and novices. 2) C++ offers features like mapping to hardware, classes, inheritance, templates, and generic programming while not requiring a garbage collector for resource management. 3) Resource management in C++ relies on resource handles, RAII, and move semantics rather than a garbage collector. Templates and generic programming are designed to be as efficient and well-specified as traditional code.

c++programming
Usability enhancements Type deduction Move semantics Lambda expressions
final
Prevent overriding:
struct Base {
virtual void f() final;
};
struct Derived : Base {
virtual void f(); // error: ’f’ overrides a ’final’ function
};
Prevent derivation:
struct Base final { };
struct Derived : Base { }; // error: ’Base’ is marked ’final’
This could be achieved in C++03 with private virtual inheritance.
11
Usability enhancements Type deduction Move semantics Lambda expressions
Explicitly deleted functions
struct Widget {
void f(double i);
void f(int) = delete;
};
Widget w;
w.f(3.0); // ok
w.f(3); // error: explicitely deleted
Explicitely deleted special member functions:
struct Widget {
Widget() = default;
Widget(const Widget&) = delete;
Widget& operator=(const Widget&) = delete;
};
11
Usability enhancements Type deduction Move semantics Lambda expressions
Unrestricted unions
In C++03, unions cannot contain any objects that define a
non-trivial constructor or destructor. C++11 lifts some restrictions.
struct Widget {
int x_;
Widget() {}
Widget(int x) : x_(x) {}
};
union U {
double f;
Widget w; // illegal in C++03, legal in C++11
};
U u; // error: call to implicitely deleted default constructor o
// note: default constructor of ’U’ is implicitely deleted
// because field ’w’ has a non-trivial default constructor
11 R
Usability enhancements Type deduction Move semantics Lambda expressions
Unrestricted unions
A constructor for the union must be manually defined:
union U {
double f;
Widget w;
U(int x) : w(x) { }
};
U u(3);
11 R

Recommended for you

C++11
C++11C++11
C++11

This document provides an overview of new features introduced in C++11, including automatic variables, decltype, rvalue references, lambda functions, variadic templates, and the concurrency library. It discusses each feature in detail and provides examples. It also outlines compiler support for C++11 in different versions of Visual Studio and references additional learning resources on C++11.

"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay

A holistic view of how the web works, with an overview of the HTTP protocol. Presented by me at null security group (http://null.co.in), Mumbai chapter meet on Aug' 27th.

tcpwwwrfc 2965
HTTP Protocol Basic
HTTP Protocol BasicHTTP Protocol Basic
HTTP Protocol Basic

The HTTP protocol is an application-level protocol used for distributed, collaborative, hypermedia information systems. It operates as a request-response protocol between clients and servers, with clients making requests using methods like GET and POST and receiving responses with status codes. Requests and responses are composed of text-based headers and messages to communicate metadata and content. Caching and cookies can be used to improve performance and maintain state in this otherwise stateless protocol.

Usability enhancements Type deduction Move semantics Lambda expressions
Strongly typed enumerations
C++03 enumerations are not type-safe. It allows the comparison between
two enum values of different enumeration types. Type-safe enumeration:
enum class Enum1 {
Val1 = 100,
Val2 // = 101
};
Override the default underlying type:
enum class Enum2 : unsigned long {Val1, Val2};
Other examples:
enum Enum3; // Underlying type cannot be determined (C++03/11)
enum class Enum4; // Underlying type is int (C++11)
11
Usability enhancements Type deduction Move semantics Lambda expressions
Template type deduction for classes
Template class:
template<typename T> // "typename" and "class" are synonymous
class Stack {
std::vector<T> elems_;
public:
void push(const T& elem) { elems_.push_back(elem); }
T top() const { return elems_.back(); }
void pop() { elems_.pop_back(); }
};
Stack<double> myStack; // T = double
Stack<int*> myStack; // T = int*
One Stack code for double and another Stack code for int*.
Usability enhancements Type deduction Move semantics Lambda expressions
Template type deduction for functions
template <typename T>
inline T max(T a, T b) {
return a > b ? a : b;
}
std::cout << max(3.0, 7.2) << std::endl; // T = double
std::cout << max("hello", "world") << std::endl;
struct Widget {
int x_;
Widget(int x) : x_(x) { }
};
Widget w1(3), w2(4);
std::cout << max(w1, w2) << std::endl;
// error: invalid operands to binary expression
Usability enhancements Type deduction Move semantics Lambda expressions
Template partial specialization for loop unrolling
The template may also be a value instead of a class, allowing e.g. for
compile-time loop unrolling, with partial specialization:
template <unsigned int N>
int factorial() {
return N * factorial<N - 1>();
}
template <>
int factorial<0>() {
return 1;
}
std::cout << factorial<4>() << std::endl; // yields 24
Since C++11, the same can be performed with constexpr.
R
11

Recommended for you

C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/

The document discusses the history and development of the internet over the past 50 years, from its origins as a network created by the United States Department of Defense to support research and education, to its subsequent commercialization and global adoption driven by the creation of the World Wide Web in the early 1990s. It grew exponentially from being used primarily by academic and military institutions to becoming integrated into the daily lives of billions of people worldwide for communication, education, commerce, and entertainment.

c++c++17
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11

C++11 introduced many new features including type deduction with auto, uniform initialization syntax, rvalue references and move semantics, improved enums, lambda expressions, and smart pointers. Type deduction with auto lets the compiler deduce the type of a variable based on its initializer. Uniform initialization uses curly braces {} and allows narrowing conversions only if explicitly cast. Rvalue references and move semantics allow moving an object to avoid expensive copies by leaving the source object in a valid but unspecified state.

c++software developmentprogramming
Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6

The document discusses IPv6 and Mobile IPv6 fundamentals, new services, and applications. It begins with an introduction to TCP/IP and the Internet and then covers the OSI and TCP/IP reference models. It describes the physical, data link, network, transport, and application layers. It focuses on IPv6 features like addressing, autoconfiguration, and mobility support through Mobile IPv6. It also discusses new applications and challenges with the transition from IPv4 to IPv6.

networking tcp/ip ipv6
Usability enhancements Type deduction Move semantics Lambda expressions
auto for variable type deduction
std::vector<int> vec{10, 11, 12, 13};
for(auto it = vec.cbegin(); it != vec.cend(); ++it) {
std::cout << *it << std::endl;
}
11
Usability enhancements Type deduction Move semantics Lambda expressions
decltype for return type deduction
template<typename T, typename U>
SomeType mul(T x, U y) {
return x*y;
}
The return type is“the type of x*y”. How can we write that?
template<typename T, typename U>
decltype(x*y) mul(T x, U y) {
return x*y;
}
It does not compile because x and y are not in scope. We can use a
trailing return type.
11
Usability enhancements Type deduction Move semantics Lambda expressions
decltype for return type deduction
Trailing return type:
template<typename T, typename U>
auto mul(T x, U y) -> decltype(x*y) {
return x*y;
}
When decltype is read, x and y are now known to the compiler. auto is
only meant to tell the compiler that it will find the return type after ->.
auto does not deduce anything.
11
Usability enhancements Type deduction Move semantics Lambda expressions
Generalized return type deduction
Since C++14, auto can deduce the return type of functions:
auto floor(double x) { return static_cast<int>(x); }
Multiple returns are allowed, but the type must be the same:
auto f() {
while(something()) {
if(expr) {
return foo() * 42;
}
}
return bar.baz();
}
14

Recommended for you

Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net

This ppt will help those who are beginner in sql server, asp.net and C# and want to learn database connectivity. So i provide them the simpler code on this universe for their database enabled web or desktop application.

sql serverweb applicationc#
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012

C++11 feels like a new language. Compared to its previous standards, C++11 packs more language features and libraries designed to make C++ programs easier to understand and faster. As the community is building up experience with the new features, new stylistic ways of using them are emerging. These styles (a.k.a. idioms) give the new language its unique flavor. This talk will present emerging idioms of using rvalue references -- a marquee feature of C++11 as many renowned experts call it. You will see how C++11 opens new possibilities to design class interfaces. Finally, you will learn some advanced use-cases of rvalue references which will likely make you feel something amiss in this flagship feature of C++11.

c++c++11best practice
Usability enhancements Type deduction Move semantics Lambda expressions
Generalized return type deduction
The return type deduction also works for recursive functions, provided the
non-recursive return statement is before the recursive call.
auto f() { return f(); } // error: return type of f is unknown
auto sum(int i) {
if (i == 1)
return i; // return type deduced to int
else
return sum(i-1)+i; // ok to call it now
}
14
Usability enhancements Type deduction Move semantics Lambda expressions
decltype(auto)
auto always deduces a non-reference type (int, double. . . ). auto&
always deduces a reference type (int&, double&. . . ). But auto cannot
conditionnaly see if the return type is a reference.
decltype can, but requires to write an expression in its parentheses.
We can use the best of both worlds with decltype(auto) which can
deduce if the type is a reference.
template<typename T, typename U>
decltype(auto) mul(T x, U y) {
return x*y;
}
14
Usability enhancements Type deduction Move semantics Lambda expressions
Copy-and-swap idiom
class Array {
int* arr_;
unsigned int size_;
public:
Array(unsigned int size = 0) : size_(size),
arr_(size > 0 ? new int[size]() : nullptr) { }
Array(const Array& other) : size_(other.size_),
arr_(other.size_ > 0 ? new int[other.size_] : nullptr)
{
std::copy(other.arr_, other.arr_ + size_, arr_);
}
~Array() { delete[] arr_; }
};
Usability enhancements Type deduction Move semantics Lambda expressions
Copy-and-swap idiom
Na¨ıve implementation of operator=:
Array& operator=(const Array& other) {
if (this != &other) {
delete [] arr_;
arr_ = nullptr;
arrSize_ = other.arrSize_;
arr_ = arrSize_ ? new int[arrSize_] : nullptr;
std::copy(other.arr_, other.arr_ + arrSize_, arr_);
}
return *this;
}

Recommended for you

C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of Class

The document discusses principles of writing good C++ code. It begins by criticizing existing code examples as "ghastly style" that are difficult to understand and maintain. It advocates for a type-rich interface style with compact data structures and well-structured algorithms. The document also emphasizes writing code with modularity, effective resource management, and thread safety by default. The presentation provides examples demonstrating these principles using C++11 features like auto, type aliases, and literals.

c++programming
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slides

This document provides an introduction to database programming and ADO.NET. It outlines the objectives and key concepts, including the hardware and software components of a client/server database system, how tables and records are organized in a relational database, common SQL statements, and the core ADO.NET classes like the connection, command, data adapter and dataset. It also covers topics like joining data from multiple tables, concurrency handling, and how ADO.NET objects can be created either from a data source or directly using code.

rupp cambodiamsmc# tutorial
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers

A intro to C++11 Smart Pointers, include unique_ptr, shared_ptr and weak_ptr.

c++11
Usability enhancements Type deduction Move semantics Lambda expressions
Copy-and-swap idiom
Issues:
1 code duplication;
2 if(this != &other) mandatory but should not occur;
3 if new[] fails, *this will have been modified (no strong exception
guarantee).
Usability enhancements Type deduction Move semantics Lambda expressions
Copy-and-swap idiom
Successful solution:
friend void swap(Array& first, Array& second) {
using std::swap; // enable ADL
swap(first.size_, second.size_);
swap(first.arr_, second.arr_);
}
Array& operator=(Array other) {
swap( *this, other );
return *this;
}
Array getArray(unsigned int size) { return Array(size); }
Array arr = getArray(4);
Usability enhancements Type deduction Move semantics Lambda expressions
Copy Elisions, Returned Value Optimization
Distinguish parameter and argument:
other is the parameter of the function;
the array returned by getArray(4) is the argument, from which the
parameter other is instanciated.
If the argument is a temporary object which will be destroyed, why make a
copy for other? The argument should become other, thereby avoiding
copy.
Most C++03 compilers could grasp this optimization opportunity
whenever possible and elude the copy.
Guideline: Do not copy the function arguments. Instead, pass them by
value and let the compiler manage the copying.
Usability enhancements Type deduction Move semantics Lambda expressions
Lvalue – Rvalue
C++11 formalized everything:
a temporary object, eligible for copy elision, is an rvalue;
otherwise it is an lvalue.
References:
an integer lvalue-reference is denoted int&;
an integer rvalue-reference is denoted int&&.
11

Recommended for you

Data structures / C++ Program examples
Data structures / C++ Program examplesData structures / C++ Program examples
Data structures / C++ Program examples

The document outlines requirements for an IT 211 Data Structures midterm. It includes 3 programming problems: 1) a program to track election results and declare a winner, 2) a program to count words, sentences, and paragraphs in input text, and 3) programs to convert between binary and decimal numbers recursively. It also provides lecture requirements on defining and implementing stacks, lists, queues, and pointers in C++.

c++programming
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond

A glimpse at some of the new features for the C++ programming languages that will be introduced by the upcoming C++17 Standard. This talk was given at the Munich C++ User Group Meetup.

c++programmingc++17
HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)
HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)
HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)

When users use our sites, they put their faith in us. They trust we will keep their information from reaching others, believe we provided the information they see, and allow us to run (web) code on their devices. Using HTTPS to secure our conversations is a key part of maintaining this trust. If that’s not motivation enough, the web’s giants are actively promoting HTTPS, requiring it for features such as HTTP2 & ServiceWorker, using it for search engine ranking and more. To make the most of the web, you need to use HTTPS. This deck reviews what HTTPS is, discusses why you should prioritize using it, and cover some of the easiest (and most cost effective) steps to get started using HTTPS

securitysmashingconfhttps
Usability enhancements Type deduction Move semantics Lambda expressions
Move constructor and move assignment operator
There are two new special member functions.
Move constructor:
Array(Array&& other) : Array() {
swap( *this, other );
}
Move assignment operator:
Array& operator=(Array&& other) {
swap( *this, other );
return *this;
}
11
Usability enhancements Type deduction Move semantics Lambda expressions
Specialize code for lvalue or rvalue
void f(int& param) {
std::cout << "lvalue" << std::endl;
}
void f(int&& param) {
std::cout << "rvalue" << std::endl;
}
int a;
f(a); // calls void f(int&)
f(std::move(a)); // calls void f(int&&)
If you can take a variable’s address, it usually is an lvalue. Otherwise it is
usually an rvalue.
11
Usability enhancements Type deduction Move semantics Lambda expressions
std::move
std::move does not move anything. It casts its parameter as an rvalue.
struct Widget {
Array arr_;
Widget(const Array& param) : arr_(std::move(param)) { }
};
Array arr(3);
Widget w(arr);
compiles but calls the copy constructor of Array instead of the move
constructor. std::move returns a const Array&& which cannot be casted
as a non-const Array&&, but can be casted as a const Array&.
Array(const Array& other); // copy constructor
Array(Array&& other); // move constructor
11
Usability enhancements Type deduction Move semantics Lambda expressions
Distinguish forwarding from rvalue references
A forwarding reference is either an lvalue reference or an rvalue reference.
A forwarding reference has the same syntax as an rvalue reference, namely
“&&”.
Rvalue references examples:
void f(Widget&& param);
Widget&& w1 = Widget();
Forwarding references:
template<typename T>
void f(T&& param);
auto&& w2 = w1;
11

Recommended for you

Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)

Look at some interesting examples of C++14 lambdas and how they interact with other language features and libraries.

lambdac++functional programming
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++

Slides from my "Gentle Introduction to Modern C++" presentation from January 20, 2015 at the Dublin C/C++ User Group: www.meetup.com/cppdug/events/219787667/ The code examples are located here: https://github.com/mihaitodor/Presentations/tree/master/cppdug/20.01.2015

programmingc++11c++
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language

C++11 introduced several new features to C++ that support modern programming patterns like lambdas, smart pointers, and move semantics. Lambdas allow for anonymous inline functions, which improve code readability and eliminate the need for functor classes. Smart pointers like unique_ptr and shared_ptr make memory management safer and more straightforward using features like move semantics and RAII. C++11 also aims to bring C++ more in line with modern hardware by supporting multi-threading and higher level abstractions while maintaining performance.

c++c++11software development
Usability enhancements Type deduction Move semantics Lambda expressions
Distinguish forwarding from rvalue references
Both forwarding references have in common the presence of type
deduction. Rvalue references do not.
template<typename T>
void f(T&& param) {
// Here we can take param’s address
// so param is always an lvalue
}
Widget w;
f(w); // param’s type is lvalue-reference Widget&
// param is lvalue
// T = Widget&
f(std::move(w)); // param’s type is rvalue-reference Widget&&
// param is lvalue
// T = Widget
11
Usability enhancements Type deduction Move semantics Lambda expressions
std::forward
void process(Widget& lValArg); // for lvalues
void process(Widget&& rValArg); // for rvalues
template<typename T>
void logAndProcess(T&& param) {
auto now = std::chrono::system_clock::now();
makeLogEntry("Calling ’process’", now);
process(param); // always calls process(Widget&)
}
Widget w;
logAndProcess(w);
logAndProcess(std::move(w));
Because param is always an lvalue, process(Widget&) is always called.
11
Usability enhancements Type deduction Move semantics Lambda expressions
std::forward
If param’s type is an rvalue-reference, we need to cast the lvalue param as
an rvalue. This is what std::forward does.
std::move always casts as an rvalue; std::forward conditionally casts as
an rvalue.
But how to distinguish? Look at T:
1 if param is an lvalue-reference, T = Widget&;
2 if param is an rvalue-reference, T = Widget.
T must be given to std::forward so it can decide whether to cast its
parameter as an rvalue or not.
process(std::forward<T>(param));
11
Usability enhancements Type deduction Move semantics Lambda expressions
Subtle forwarding and rvalue references
template<typename T>
class vector {
public:
void push_back(T&& x);
};
is not a forwarding reference. Writing std::vector<Widget> v; causes
the template to be instanciated as
class vector<Widget> {
public:
void push_back(Widget&& x);
};
which involves no type deduction.
11 R

Recommended for you

Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]

The document provides an overview of the C programming language. It begins by explaining that Objective-C extends standard ANSI C with object-oriented capabilities. It then discusses why C remains important today due to its use in libraries, operating systems, and as the base for many other popular languages. The document proceeds to cover basic C concepts like variables, data types, functions, flow control, pointers, memory allocation, and I/O parameters. It emphasizes that C provides high performance with a minimal footprint while abstracting away the CPU and memory.

codemashcsdk
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx

Object Oriented Programming using C++: Ch08 Operator Overloading

object oriented programming
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++

This document provides an overview of C++ control statements, functions, and storage classes. It discusses various loops like while, for, and do-while loops. It also covers decision making statements such as if-else, if-else-if-else, switch statements, and unconditional statements like break, continue, and goto. The document then discusses functions, recursion, and inline functions. Finally, it summarizes different storage classes in C++ like auto, register, static, external, and mutable and provides examples of each.

c++ module 2
Usability enhancements Type deduction Move semantics Lambda expressions
Subtle forwarding and rvalue references
A template forwarding reference must have the form T&&. Hence, the two
following references do not qualify for being forwarding references.
template<typename T>
void f(const T&& param);
template<typename T>
void f(std::vector<T>&& param);
11 R
Usability enhancements Type deduction Move semantics Lambda expressions
Subtle forwarding and rvalue references
The variadic templates of emplace involve type deduction.
template<typename T>
class vector {
public:
template<typename... Args>
void emplace(Args&& args);
};
11 R
Usability enhancements Type deduction Move semantics Lambda expressions
Implementation of std::move in C++11
template<typename T>
typename remove_reference<T>::type&& move(T&& param) {
using ReturnType = typename remove_reference<T>::type&&;
return static_cast<ReturnType>(param);
}
param is a forwarding reference:
if param is an lvalue-reference, T = Widget&;
if param is an rvalue-reference, T = Widget.
Steps:
1 remove_reference<T>::type returns Widget;
2 remove_reference<T>::type&& returns Widget&&;
3 static_cast<Widget&&> casts param as an rvalue.
11 R
Usability enhancements Type deduction Move semantics Lambda expressions
Implementation of std::move in C++14
std::remove_reference_t<T> replaces
typename remove_reference<T>::type.
std::move can elegantly be written as
template<typename T>
decltype(auto) move(T&& param) {
using ReturnType = remove_reference_t<T>&&;
return static_cast<ReturnType>(param);
}
14 R

Recommended for you

Functions.pptx, programming language in c
Functions.pptx, programming language in cFunctions.pptx, programming language in c
Functions.pptx, programming language in c

Programming in c

Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#

The document provides information about C and C Sharp programming languages. It discusses the history, features, data types, loops, conditional statements, functions, arrays, pointers, object-oriented concepts like inheritance, encapsulation, polymorphism in both the languages. It also highlights some advantages of C Sharp over C like automatic memory management, no need of header files etc.

Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c

This document provides an introduction to the C programming language. It discusses fundamental C elements like data types, variables, constants, operators, and input/output functions. It explains how a basic C program is structured and compiled. Examples are provided to demonstrate simple C statements, arithmetic expressions, and how to write and run a first program that prints text. The key topics covered include basic syntax, program structure, data types, identifiers, operators, and input/output functions like printf() and scanf().

c++ programing
Usability enhancements Type deduction Move semantics Lambda expressions
Lambda expressions
auto lambda = [](int x, int y) -> int { return x + y; };
std::cout << lambda(2, 3) << std::endl;
Components:
(int x, int y) is the parameters list;
int after -> is the return type;
{...} is the lambda body.
A lambda can be executed upon declaration with trailing“()”:
std::cout
<< [](int x, int y) -> int { return x + y; }(2, 3)
<< std::endl;
11
Usability enhancements Type deduction Move semantics Lambda expressions
std::for each and std::transform
Apply a lambda to each element of an iterator:
void f(std::vector<int>& v) {
std::for_each(v.begin(), v.end(),
[](int p) { std::cout << p << std::endl; });
}
Modify each element with a lambda:
void f(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
[](double d) { return d < 0.00001 ? 0 : d; });
}
C++03 already had std::for_each and std::transform, but
cumbersome functors were necessary since lambdas were not available.
11
Usability enhancements Type deduction Move semantics Lambda expressions
std::for each and std::transform
If the body is not a single return expression, the type has to be explicitely
stated:
void f(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
[](double d) -> double {
if (d < 0.0001)
return 0;
else
return d;
});
}
11
Usability enhancements Type deduction Move semantics Lambda expressions
Lambda captures
[] allows to capture other variables from the scope.
void f(std::vector<double>& v, double epsilon) {
std::transform(v.begin(), v.end(), v.begin(),
[epsilon](double d) -> double {
if (d < epsilon)
return 0;
else
return d;
});
}
We can capture by both reference and value.
11

Recommended for you

Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04

Object Oriented Design and Programming , Unit-04, SRM University, II Semester, Regulation 2021

srmoodpr2021
C programming session 01
C programming session 01C programming session 01
C programming session 01

The document discusses various topics related to C language including: - Benefits and features of C like low-level operations, structured programming, and modular programming - Data types in C like fundamental types (char, int, float), derived types, and defining variables - Structure of C functions including single-level and multiple-level functions - Input-output functions in C like character-based (getc, putc), string-based (gets, puts)

C++ Advanced
C++ AdvancedC++ Advanced
C++ Advanced

The document discusses C++0x standard library extensions (TR1) and advanced C++ techniques. It provides an overview of new features in C++0x related to the core language like type inference, lambda functions, and rvalue references. It also discusses changes to the C++ standard library like tuples, hash tables, smart pointers, and other containers. The document is intended as course material covering these new C++0x features.

Usability enhancements Type deduction Move semantics Lambda expressions
Generalized lambda captures
An element of the capture can be initialized with =. This allows renaming
of variables and to capture by moving.
int x = 4;
auto y = [&r = x, x = x+1]() -> int {
r += 2;
return x+2;
}(); // Updates ::x to 6, and initializes y to 7
std::unique_ptr<int> ptr(new int(10));
auto lambda = [value = std::move(ptr)] { return *value; };
std::unique_ptr can be moved but not copied. Capture by move is the
only way to capture a std::unique_ptr.
14
Usability enhancements Type deduction Move semantics Lambda expressions
Generic lambdas
Lambda function parameters may be declared auto.
auto lambda = [](auto x, auto y) { return x + y; };
14
Usability enhancements Type deduction Move semantics Lambda expressions
Improved return type deduction
C++14 allows deduced return types for every function, not only those of
the form return expression.
void f(std::vector<double>& v, double epsilon) {
std::transform(v.begin(), v.end(), v.begin(),
[epsilon](auto d) {
if (d < epsilon)
return 0;
else
return d;
});
}
14
Usability enhancements Type deduction Move semantics Lambda expressions
Remaining modern C++ topics
type traits (std::enable if, std::is pointer. . . );
smart pointers;
threading facilities;
noexcept;
std::function;
std::bind and std::ref;
std::regex;
extern template;
inline namespace. . .

Recommended for you

Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup

This document discusses functions and header/source files in C++. It covers declarations, definitions, and the differences between them. Declarations introduce names and specify types, while definitions also fully specify the entity. Declarations allow interfaces to be specified. Headers contain declarations to share interfaces between parts of a program. Functions are described as units of operation that can take parameters and return values. The document also discusses scopes, namespaces, and storage classes like static.

c++computer
C++ language
C++ languageC++ language
C++ language

The document provides an overview of the C++ programming language. It discusses that C++ was created by Bjarne Stroustrup to provide Simula's facilities for program organization together with C's efficiency and flexibility for systems programming. The document outlines key C++ features like classes, templates, operator overloading, and exceptions. It also covers topics like class definitions, constructors, destructors, streams, and compiling/linking C++ programs.

Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server

The document provides suggestions for using various new C++11 language features in ATS coding, focusing on features that are most useful. It discusses nullptr, auto, range-based for loops, delegating constructors, prohibiting/defaulting methods, member initialization, override, explicit conversion operators, std::unique_ptr, lambdas, std::function, constexpr, and provides code examples for many of these features. The overall aim is to take advantage of new language features to improve ATS code without overusing them in a way that makes the code harder to understand.

falltraffic serversummit

More Related Content

What's hot

Loops in c language
Loops in c languageLoops in c language
Loops in c language
tanmaymodi4
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
Effective Modern C++
Effective Modern C++Effective Modern C++
Effective Modern C++
Wang Hsiangkai
 
Toolchain
ToolchainToolchain
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
xu liwei
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
Dipta Saha
 
Linux Ethernet device driver
Linux Ethernet device driverLinux Ethernet device driver
Linux Ethernet device driver
艾鍗科技
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
Modern C++
Modern C++Modern C++
Modern C++
Richard Thomson
 
Loops in c
Loops in cLoops in c
Embedded linux network device driver development
Embedded linux network device driver developmentEmbedded linux network device driver development
Embedded linux network device driver development
Amr Ali (ISTQB CTAL Full, CSM, ITIL Foundation)
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Advanced C - Part 1
Advanced C - Part 1 Advanced C - Part 1
Clanguage
ClanguageClanguage
Clanguage
Vidyacenter
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
C++11
C++11C++11
Unix v6 Internals
Unix v6 InternalsUnix v6 Internals
Q2.12: Debugging with GDB
Q2.12: Debugging with GDBQ2.12: Debugging with GDB
Q2.12: Debugging with GDB
Linaro
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 

What's hot (20)

Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Effective Modern C++
Effective Modern C++Effective Modern C++
Effective Modern C++
 
Toolchain
ToolchainToolchain
Toolchain
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
 
Linux Ethernet device driver
Linux Ethernet device driverLinux Ethernet device driver
Linux Ethernet device driver
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Modern C++
Modern C++Modern C++
Modern C++
 
Loops in c
Loops in cLoops in c
Loops in c
 
Embedded linux network device driver development
Embedded linux network device driver developmentEmbedded linux network device driver development
Embedded linux network device driver development
 
Exception handling
Exception handlingException handling
Exception handling
 
Advanced C - Part 1
Advanced C - Part 1 Advanced C - Part 1
Advanced C - Part 1
 
Clanguage
ClanguageClanguage
Clanguage
 
Inline function
Inline functionInline function
Inline function
 
C++11
C++11C++11
C++11
 
Unix v6 Internals
Unix v6 InternalsUnix v6 Internals
Unix v6 Internals
 
Q2.12: Debugging with GDB
Q2.12: Debugging with GDBQ2.12: Debugging with GDB
Q2.12: Debugging with GDB
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 

Viewers also liked

Web I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolWeb I - 05 - HTTP Protocol
Web I - 05 - HTTP Protocol
Randy Connolly
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
Stephane Gleizes
 
TCP/IP
TCP/IPTCP/IP
Bjarne essencegn13
Bjarne essencegn13Bjarne essencegn13
Bjarne essencegn13
Hunde Gurmessa
 
C++11
C++11C++11
"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay
Bipin Upadhyay
 
HTTP Protocol Basic
HTTP Protocol BasicHTTP Protocol Basic
HTTP Protocol Basic
Chuong Mai
 
C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/
Sławomir Zborowski
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11
Uilian Ries
 
Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6
Rodolfo Kohn
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net
Hemant Sankhla
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
Sumant Tambe
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of Class
Yogendra Rampuria
 
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slides
Sami Mut
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers
chchwy Chang
 
Data structures / C++ Program examples
Data structures / C++ Program examplesData structures / C++ Program examples
Data structures / C++ Program examples
Kevin III
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
ComicSansMS
 
HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)
HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)
HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)
Guy Podjarny
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 

Viewers also liked (20)

Web I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolWeb I - 05 - HTTP Protocol
Web I - 05 - HTTP Protocol
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
 
TCP/IP
TCP/IPTCP/IP
TCP/IP
 
Bjarne essencegn13
Bjarne essencegn13Bjarne essencegn13
Bjarne essencegn13
 
C++11
C++11C++11
C++11
 
"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay"Http protocol and other stuff" by Bipin Upadhyay
"Http protocol and other stuff" by Bipin Upadhyay
 
HTTP Protocol Basic
HTTP Protocol BasicHTTP Protocol Basic
HTTP Protocol Basic
 
C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/C++17 - the upcoming revolution (Code::Dive 2015)/
C++17 - the upcoming revolution (Code::Dive 2015)/
 
Elements of C++11
Elements of C++11Elements of C++11
Elements of C++11
 
Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6Networking - TCP/IP stack introduction and IPv6
Networking - TCP/IP stack introduction and IPv6
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
 
C++14 Overview
C++14 OverviewC++14 Overview
C++14 Overview
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of Class
 
C# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slidesC# Tutorial MSM_Murach chapter-17-slides
C# Tutorial MSM_Murach chapter-17-slides
 
C++11 smart pointers
C++11 smart pointersC++11 smart pointers
C++11 smart pointers
 
Data structures / C++ Program examples
Data structures / C++ Program examplesData structures / C++ Program examples
Data structures / C++ Program examples
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)
HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)
HTTPS: What, Why and How (SmashingConf Freiburg, Sep 2015)
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 

Similar to Modern c++ (C++ 11/14)

Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
Mihai Todor
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
mspline
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
msharshitha03s
 
Functions.pptx, programming language in c
Functions.pptx, programming language in cFunctions.pptx, programming language in c
Functions.pptx, programming language in c
floraaluoch3
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
shubhra chauhan
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
sivakumarmcs
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
Dushmanta Nath
 
C++ Advanced
C++ AdvancedC++ Advanced
C++ Advanced
Vivek Das
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 
C++ language
C++ languageC++ language
C++ language
Hamza Asif
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
Apache Traffic Server
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
Thooyavan Venkatachalam
 
C++
C++C++
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
somu rajesh
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
Divyanshu Dubey
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
PriyadarshiniS28
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
Prabhu D
 

Similar to Modern c++ (C++ 11/14) (20)

Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Functions.pptx, programming language in c
Functions.pptx, programming language in cFunctions.pptx, programming language in c
Functions.pptx, programming language in c
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 
Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04Object Oriented Design and Programming Unit-04
Object Oriented Design and Programming Unit-04
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
C++ Advanced
C++ AdvancedC++ Advanced
C++ Advanced
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
C++ language
C++ languageC++ language
C++ language
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C++
C++C++
C++
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 

More from Geeks Anonymes

Programmer sous Unreal Engine
Programmer sous Unreal EngineProgrammer sous Unreal Engine
Programmer sous Unreal Engine
Geeks Anonymes
 
Implémentation efficace et durable de processus métiers complexes
Implémentation efficace et durable de processus métiers complexesImplémentation efficace et durable de processus métiers complexes
Implémentation efficace et durable de processus métiers complexes
Geeks Anonymes
 
Managing Open Source Licenses (Geeks Anonymes)
Managing Open Source Licenses (Geeks Anonymes)Managing Open Source Licenses (Geeks Anonymes)
Managing Open Source Licenses (Geeks Anonymes)
Geeks Anonymes
 
Reprendre le contrôle de ses données
Reprendre le contrôle de ses donnéesReprendre le contrôle de ses données
Reprendre le contrôle de ses données
Geeks Anonymes
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
Geeks Anonymes
 
Le rôle du testeur et le Blackbox testing
Le rôle du testeur et le Blackbox testingLe rôle du testeur et le Blackbox testing
Le rôle du testeur et le Blackbox testing
Geeks Anonymes
 
Kubernetes
KubernetesKubernetes
Kubernetes
Geeks Anonymes
 
Vulnérabilités au cœur des applications Web, menaces et contre-mesures
 Vulnérabilités au cœur des applications Web, menaces et contre-mesures Vulnérabilités au cœur des applications Web, menaces et contre-mesures
Vulnérabilités au cœur des applications Web, menaces et contre-mesures
Geeks Anonymes
 
191121 philippe teuwen cryptographie et attaques materielles
191121 philippe teuwen cryptographie et attaques materielles191121 philippe teuwen cryptographie et attaques materielles
191121 philippe teuwen cryptographie et attaques materielles
Geeks Anonymes
 
"Surfez couverts !" - Conseils de Cyber securité
"Surfez couverts !" - Conseils de Cyber securité "Surfez couverts !" - Conseils de Cyber securité
"Surfez couverts !" - Conseils de Cyber securité
Geeks Anonymes
 
Introduction au développement mobile - développer une application iOS et Andr...
Introduction au développement mobile - développer une application iOS et Andr...Introduction au développement mobile - développer une application iOS et Andr...
Introduction au développement mobile - développer une application iOS et Andr...
Geeks Anonymes
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
Geeks Anonymes
 
Test your code
Test your codeTest your code
Test your code
Geeks Anonymes
 
Intelligence artificielle et propriété intellectuelle
Intelligence artificielle et propriété intellectuelleIntelligence artificielle et propriété intellectuelle
Intelligence artificielle et propriété intellectuelle
Geeks Anonymes
 
Pour une histoire plophonique du jeu video
Pour une histoire plophonique du jeu videoPour une histoire plophonique du jeu video
Pour une histoire plophonique du jeu video
Geeks Anonymes
 
Become Rick and famous, thanks to Open Source
Become Rick and famous, thanks to Open SourceBecome Rick and famous, thanks to Open Source
Become Rick and famous, thanks to Open Source
Geeks Anonymes
 
Reconnaissance vocale et création artistique
Reconnaissance vocale et création artistiqueReconnaissance vocale et création artistique
Reconnaissance vocale et création artistique
Geeks Anonymes
 
Natural Language Processing
Natural Language ProcessingNatural Language Processing
Natural Language Processing
Geeks Anonymes
 
Sécurité, GDPR : vos données ont de la valeur
Sécurité, GDPR : vos données ont de la valeur Sécurité, GDPR : vos données ont de la valeur
Sécurité, GDPR : vos données ont de la valeur
Geeks Anonymes
 
Modern sql
Modern sqlModern sql
Modern sql
Geeks Anonymes
 

More from Geeks Anonymes (20)

Programmer sous Unreal Engine
Programmer sous Unreal EngineProgrammer sous Unreal Engine
Programmer sous Unreal Engine
 
Implémentation efficace et durable de processus métiers complexes
Implémentation efficace et durable de processus métiers complexesImplémentation efficace et durable de processus métiers complexes
Implémentation efficace et durable de processus métiers complexes
 
Managing Open Source Licenses (Geeks Anonymes)
Managing Open Source Licenses (Geeks Anonymes)Managing Open Source Licenses (Geeks Anonymes)
Managing Open Source Licenses (Geeks Anonymes)
 
Reprendre le contrôle de ses données
Reprendre le contrôle de ses donnéesReprendre le contrôle de ses données
Reprendre le contrôle de ses données
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Le rôle du testeur et le Blackbox testing
Le rôle du testeur et le Blackbox testingLe rôle du testeur et le Blackbox testing
Le rôle du testeur et le Blackbox testing
 
Kubernetes
KubernetesKubernetes
Kubernetes
 
Vulnérabilités au cœur des applications Web, menaces et contre-mesures
 Vulnérabilités au cœur des applications Web, menaces et contre-mesures Vulnérabilités au cœur des applications Web, menaces et contre-mesures
Vulnérabilités au cœur des applications Web, menaces et contre-mesures
 
191121 philippe teuwen cryptographie et attaques materielles
191121 philippe teuwen cryptographie et attaques materielles191121 philippe teuwen cryptographie et attaques materielles
191121 philippe teuwen cryptographie et attaques materielles
 
"Surfez couverts !" - Conseils de Cyber securité
"Surfez couverts !" - Conseils de Cyber securité "Surfez couverts !" - Conseils de Cyber securité
"Surfez couverts !" - Conseils de Cyber securité
 
Introduction au développement mobile - développer une application iOS et Andr...
Introduction au développement mobile - développer une application iOS et Andr...Introduction au développement mobile - développer une application iOS et Andr...
Introduction au développement mobile - développer une application iOS et Andr...
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Test your code
Test your codeTest your code
Test your code
 
Intelligence artificielle et propriété intellectuelle
Intelligence artificielle et propriété intellectuelleIntelligence artificielle et propriété intellectuelle
Intelligence artificielle et propriété intellectuelle
 
Pour une histoire plophonique du jeu video
Pour une histoire plophonique du jeu videoPour une histoire plophonique du jeu video
Pour une histoire plophonique du jeu video
 
Become Rick and famous, thanks to Open Source
Become Rick and famous, thanks to Open SourceBecome Rick and famous, thanks to Open Source
Become Rick and famous, thanks to Open Source
 
Reconnaissance vocale et création artistique
Reconnaissance vocale et création artistiqueReconnaissance vocale et création artistique
Reconnaissance vocale et création artistique
 
Natural Language Processing
Natural Language ProcessingNatural Language Processing
Natural Language Processing
 
Sécurité, GDPR : vos données ont de la valeur
Sécurité, GDPR : vos données ont de la valeur Sécurité, GDPR : vos données ont de la valeur
Sécurité, GDPR : vos données ont de la valeur
 
Modern sql
Modern sqlModern sql
Modern sql
 

Recently uploaded

Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdfResponsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Trackobit
 
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Splunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptxSplunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptx
sudsdeep
 
Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
Mitchell Marsh
 
Attendance Tracking From Paper To Digital
Attendance Tracking From Paper To DigitalAttendance Tracking From Paper To Digital
Attendance Tracking From Paper To Digital
Task Tracker
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
ssuser2b426d1
 
Break data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud ConnectorsBreak data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud Connectors
confluent
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
ThousandEyes
 
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
Hironori Washizaki
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Asher Sterkin
 
MVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptxMVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptx
Mitchell Marsh
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
sudsdeep
 
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdfdachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
DNUG e.V.
 
Shivam Pandit working on Php Web Developer.
Shivam Pandit working on Php Web Developer.Shivam Pandit working on Php Web Developer.
Shivam Pandit working on Php Web Developer.
shivamt017
 
CViewSurvey Digitech Pvt Ltd that works on a proven C.A.A.G. model.
CViewSurvey Digitech Pvt Ltd that  works on a proven C.A.A.G. model.CViewSurvey Digitech Pvt Ltd that  works on a proven C.A.A.G. model.
CViewSurvey Digitech Pvt Ltd that works on a proven C.A.A.G. model.
bhatinidhi2001
 
dachnug51 - All you ever wanted to know about domino licensing.pdf
dachnug51 - All you ever wanted to know about domino licensing.pdfdachnug51 - All you ever wanted to know about domino licensing.pdf
dachnug51 - All you ever wanted to know about domino licensing.pdf
DNUG e.V.
 
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
karim wahed
 
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
Semiosis Software Private Limited
 
NBFC Software: Optimize Your Non-Banking Financial Company
NBFC Software: Optimize Your Non-Banking Financial CompanyNBFC Software: Optimize Your Non-Banking Financial Company
NBFC Software: Optimize Your Non-Banking Financial Company
NBFC Softwares
 
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdfIndependence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
Livetecs LLC
 

Recently uploaded (20)

Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdfResponsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
Responsibilities of Fleet Managers and How TrackoBit Can Assist.pdf
 
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
Abortion pills in Fujairah *((+971588192166*)☎️)¥) **Effective Abortion Pills...
 
Splunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptxSplunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptx
 
Overview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptxOverview of ERP - Mechlin Technologies.pptx
Overview of ERP - Mechlin Technologies.pptx
 
Attendance Tracking From Paper To Digital
Attendance Tracking From Paper To DigitalAttendance Tracking From Paper To Digital
Attendance Tracking From Paper To Digital
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
 
Break data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud ConnectorsBreak data silos with real-time connectivity using Confluent Cloud Connectors
Break data silos with real-time connectivity using Confluent Cloud Connectors
 
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
Cisco Live Announcements: New ThousandEyes Release Highlights - July 2024
 
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
 
MVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptxMVP Mobile Application - Codearrest.pptx
MVP Mobile Application - Codearrest.pptx
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
 
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdfdachnug51 - HCL Sametime 12 as a Software Appliance.pdf
dachnug51 - HCL Sametime 12 as a Software Appliance.pdf
 
Shivam Pandit working on Php Web Developer.
Shivam Pandit working on Php Web Developer.Shivam Pandit working on Php Web Developer.
Shivam Pandit working on Php Web Developer.
 
CViewSurvey Digitech Pvt Ltd that works on a proven C.A.A.G. model.
CViewSurvey Digitech Pvt Ltd that  works on a proven C.A.A.G. model.CViewSurvey Digitech Pvt Ltd that  works on a proven C.A.A.G. model.
CViewSurvey Digitech Pvt Ltd that works on a proven C.A.A.G. model.
 
dachnug51 - All you ever wanted to know about domino licensing.pdf
dachnug51 - All you ever wanted to know about domino licensing.pdfdachnug51 - All you ever wanted to know about domino licensing.pdf
dachnug51 - All you ever wanted to know about domino licensing.pdf
 
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
AWS Cloud Practitioner Essentials (Second Edition) (Arabic) Course Introducti...
 
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
React vs Next js: Which is Better for Web Development? - Semiosis Software Pr...
 
NBFC Software: Optimize Your Non-Banking Financial Company
NBFC Software: Optimize Your Non-Banking Financial CompanyNBFC Software: Optimize Your Non-Banking Financial Company
NBFC Software: Optimize Your Non-Banking Financial Company
 
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdfIndependence Day Hasn’t Always Been a U.S. Holiday.pdf
Independence Day Hasn’t Always Been a U.S. Holiday.pdf
 

Modern c++ (C++ 11/14)

  • 1. Usability enhancements Type deduction Move semantics Lambda expressions Modern C++ (C++11/14) Geeks Anonymes Damien Gerard October 19th, 2016
  • 2. Usability enhancements Type deduction Move semantics Lambda expressions Introduction “C++11 feels like a new language.” Bjarne Stroustrup (inventor of C++)
  • 3. Usability enhancements Type deduction Move semantics Lambda expressions Labels 11 since C++11 14 since C++14 17 since C++17 R that ain’t for kids
  • 4. Usability enhancements Type deduction Move semantics Lambda expressions Range-based for loop for statement syntax extended to allow for easy iteration over a range of elements: int myArray[5] = {1, 2, 3, 4, 5}; for(int x : myArray) { std::cout << x << std::endl; } for(int& x : myArray) { x *= 2; // double value and save } for(auto& x : myArray) { // auto = int x *= 2; } 11
  • 5. Usability enhancements Type deduction Move semantics Lambda expressions auto Constant iterator over a vector: std::vector<int> vec(4,100); // four ints with value 100 for(std::vector<int>::const_iterator it = vec.cbegin(); it != vec.cend(); ++it) { std::cout << *it << std::endl; } auto for type deduction: std::vector<int> vec(4,100); // four ints with value 100 for(auto it = vec.cbegin(); it != vec.cend(); ++it) { std::cout << *it << std::endl; } 11
  • 6. Usability enhancements Type deduction Move semantics Lambda expressions Null pointer literal Constant 0 had the double role of constant integer and null pointer constant. void f(int*); void f(int); f(NULL); // calls f(int) or error: ambiguous If NULL defined as 0, f(NULL) calls f(int). Most programmers would expect f(int*) because NULL means a null pointer in their mind.
  • 7. Usability enhancements Type deduction Move semantics Lambda expressions Null pointer literal nullptr is a pointer literal of type nullptr_t, which is implicitly convertible and comparable to any pointer type. It is not implicitly convertible or comparable to integral types, except for bool. char* pc = nullptr; // compiles int* pi = nullptr; // compiles bool b = nullptr; // compiles, b is false int i = nullptr; // error f(nullptr); // calls f(int*), not f(int) f(nullptr_t) will actually call f(int*) using implicit conversion. 11
  • 8. Usability enhancements Type deduction Move semantics Lambda expressions Initializer lists C++03 inherited the initializer-list feature from C. struct Widget { float first; int second; }; Widget w1 = {0.43f, 10}; // first=0.43f and second=10 Widget w2[] = {{13.4f, 3}, {43.2f, 29}}; Useful albeit limited to Plain Old Data (POD) structs and classes.
  • 9. Usability enhancements Type deduction Move semantics Lambda expressions Uniform initialization Initializer-lists for all classes, including standard containers. std::vector<std::string> v = { "Hello", "world" }; std::vector<std::string> v({ "Hello", "world" }); std::vector<std::string> v{ "Hello", "world" }; int val = 5.2; // automatic narrowing int val{5.2}; // error or warning: type ’double’ // cannot be narrowed to ’int’ in initializer list // insert an explicit static cast static_cast<int>( ) Widget getWidget() { return {0.43f, 10}; // no need for explicit type } 11
  • 10. Usability enhancements Type deduction Move semantics Lambda expressions Most vexing parse struct Widget { Widget(); }; struct WidgetKeeper { WidgetKeeper(Widget w); }; WidgetKeeper wKeeper(Widget()); // most vexing parse Ambiguous call: 1 new instance of Widget, sent to constructor of WidgetKeeper; 2 function declaration: name“wKeeper”, return type WidgetKeeper, single (unnamed) parameter which is a function returning type Widget.
  • 11. Usability enhancements Type deduction Move semantics Lambda expressions Most vexing parse Most developers expect the first, but the C++ standard requires it to be interpreted as the second. Workaround in C++03 to ensure the first interpretation: WidgetKeeper time_keeper( (Widget()) ); C++11’s uniform initialization syntax: WidgetKeeper time_keeper{Widget{}}; 11
  • 12. Usability enhancements Type deduction Move semantics Lambda expressions Returning multiple values void divide(int dividend, int divisor, int& quotient, int& remainder) { quotient = dividend / divisor; remainder = dividend % divisor; } Or even worse, return quotient through the returned value and remainder as a reference variable: int divide(int dividend, int divisor, int& remainder) { remainder = dividend % divisor; return dividend / divisor; }
  • 13. Usability enhancements Type deduction Move semantics Lambda expressions Returning multiple values Or, but rather heavy: struct divideResult { int quotient; int remainder; }; divideResult divide(int dividend, int divisor) { return { dividend / divisor, dividend % divisor }; } divideResult result = divide(10, 3); std::cout << result.quotient << std::endl; std::cout << result.remainder << std::endl; 11
  • 14. Usability enhancements Type deduction Move semantics Lambda expressions Returning multiple values std::tuple<int,int> divide(int dividend, int divisor) { return std::make_tuple(dividend / divisor, dividend % divisor); } int quotient, remainder; std::tie(quotient, remainder) = divide(10, 3); C++17’s structured bindings (Clang-4.0 only, as of today): auto [quotient, remainder] = divide(10, 3); std::cout << quotient << std::endl; std::cout << remainder << std::endl; 11 17
  • 15. Usability enhancements Type deduction Move semantics Lambda expressions std::unordered * std::set, map, multiset, multimap associative containers are implemented as balanced trees. The std::unordered_set, unordered_map, unordered_multiset, unordered_multimap alternatives are implemented as hash tables. Including hash tables was one of the most recurring requests. It was not adopted in C++03 due to time constraints only. Although hash tables are less efficient than a balanced tree in the worst case (in the presence of many collisions), they perform better in many real applications. 11
  • 16. Usability enhancements Type deduction Move semantics Lambda expressions emplace, emplace back emplace and emplace_back can construct an element in-place. auto employees = std::unordered_map<int, std::string>{}; auto e1 = std::pair<int, std::string>{1, "John Smith"}; employees.insert(e1); employees.insert(std::make_pair(2, "Mary Jones")); employees.emplace(3, "James Brown"); // construct in-place for (const auto& e : employees) { std::cout << e.first << ": " << e.second << std::endl; } 11
  • 17. Usability enhancements Type deduction Move semantics Lambda expressions In-class initialization In C++03, in-class initialization on static const members of integral or enumeration type only. struct Widget { static const int a = 7; // compiles float b = 7.2; // error: not static const integral const int c = 7; // error: not static static int d = 7; // error: not const static const float e = 7.2; // error: not integral const static int arr[] = { 1, 2, 3 }; // error: must be initialized out of line };
  • 18. Usability enhancements Type deduction Move semantics Lambda expressions In-class initialization C++11 allows some of them: struct Widget { static const int a = 7; float b = 7.2; const int c = 7; static int d = 7; // still fails static float e = 7.2; // still fails constexpr static int arr[] = { 1, 2, 3 }; constexpr static std::complex<double> f = { 1, 2 }; }; A non-const static variable still has to be initialized outside the class with int Widget::d = 7; float Widget::e = 7.2; 11
  • 19. Usability enhancements Type deduction Move semantics Lambda expressions ODR-use An object is odr-used if its address is taken, or a reference is bound to it. If a const or constexpr static data member is odr-used, a redefinition (no initializer permitted) at namespace scope is required. struct Widget { static const int n = 1; static constexpr int m = 4; }; const int& f(const int& r); // call f(Widget::n) or f(Widget::m) somewhere // redefinition at namespace scope required: const int Widget::n, Widget::m; C++17 alleviates this constraint for constexpr. A static data member declared constexpr is implicitly inline and needs not be redeclared at namespace scope. R 11 17
  • 20. Usability enhancements Type deduction Move semantics Lambda expressions constexpr Declare something that can be evaluated down to a constant: constexpr double pi() { return std::atan(1) * 4; } constexpr double getCircleSurface(double r) { return pi() * r * r; } const double circleSurface = getCircleSurface(0.5); or const float oneEighty = degreesToRadians(180.0f); Since C++14, constexpr functions may have more than one line. 11 14
  • 21. Usability enhancements Type deduction Move semantics Lambda expressions Call other constructors In C++03, other constructors could not be called. Workaround: call a common member function class Widget { int number_; void construct(int number) { number_ = number; } public: Widget(int number) { construct(number); } Widget() { construct(42); } };
  • 22. Usability enhancements Type deduction Move semantics Lambda expressions Call other constructors Wrong workaround: class Widget { int number_; public: Widget(int number) : number_(number) { } Widget() { Widget(42); // this->number_ = 0 or something undefined } }; What is wanted but does not compile: Widget() : Widget(42) { }
  • 23. Usability enhancements Type deduction Move semantics Lambda expressions Call other constructors In C++11 other peer constructors may be called (“delegation”). class Widget { int number_; public: Widget(int number) : number_(number) { } Widget() : Widget(42) { } }; An object is constructed once any constructor finishes execution. Since multiple constructors are allowed to execute, each delegating constructor will be executing on a fully constructed object of its own type. 11
  • 24. Usability enhancements Type deduction Move semantics Lambda expressions Call or import base class constructors Call base class constructor: struct Base { Base(int number); }; struct Derived : Base { Derived(int number) : Base(number) { } }; Import all base class constructors: struct Derived : Base { using Base::Base }; // can call Derived(42); 11
  • 25. Usability enhancements Type deduction Move semantics Lambda expressions Override a base class method struct Animal { char* say() const { return "??"; } }; struct Cow : Animal { char* say() const { return "moo"; } }; struct Pig : Animal { char* say() const { return "oink"; } }; std::vector<Animal*> animals{new Cow, new Pig}; for(const Animal* a : animals) { std::cout << a->say() << std::endl; } Prints“??” for both the cow and the pig.
  • 26. Usability enhancements Type deduction Move semantics Lambda expressions Dynamic polymorphism struct Animal { virtual char* say() const { return "??"; } }; struct Cow : Animal { virtual char* say() const { return "moo"; } }; struct Pig : Animal { virtual char* say() const { return "oink"; } }; Prints“moo”and“oink”. What if const is forgotten in the Pig’s say()? It will compile and print“moo”and“??”.
  • 27. Usability enhancements Type deduction Move semantics Lambda expressions Typo in derived class The following code compiles but contains no virtual function overrides. struct Base { void f1() const; virtual void f2() const; virtual void f3(int x); } struct Derived : Base { void f1() const; virtual void f2(); virtual void f3(unsigned int x); }
  • 28. Usability enhancements Type deduction Move semantics Lambda expressions overrides Make explicit that a derived class is expected to override a base class: struct Derived : Base { void f1() const override; virtual void f2() override; virtual void f3(unsigned int x) override; } The compiler will complain about all the overriding-related issues. 11
  • 29. Usability enhancements Type deduction Move semantics Lambda expressions final Prevent overriding: struct Base { virtual void f() final; }; struct Derived : Base { virtual void f(); // error: ’f’ overrides a ’final’ function }; Prevent derivation: struct Base final { }; struct Derived : Base { }; // error: ’Base’ is marked ’final’ This could be achieved in C++03 with private virtual inheritance. 11
  • 30. Usability enhancements Type deduction Move semantics Lambda expressions Explicitly deleted functions struct Widget { void f(double i); void f(int) = delete; }; Widget w; w.f(3.0); // ok w.f(3); // error: explicitely deleted Explicitely deleted special member functions: struct Widget { Widget() = default; Widget(const Widget&) = delete; Widget& operator=(const Widget&) = delete; }; 11
  • 31. Usability enhancements Type deduction Move semantics Lambda expressions Unrestricted unions In C++03, unions cannot contain any objects that define a non-trivial constructor or destructor. C++11 lifts some restrictions. struct Widget { int x_; Widget() {} Widget(int x) : x_(x) {} }; union U { double f; Widget w; // illegal in C++03, legal in C++11 }; U u; // error: call to implicitely deleted default constructor o // note: default constructor of ’U’ is implicitely deleted // because field ’w’ has a non-trivial default constructor 11 R
  • 32. Usability enhancements Type deduction Move semantics Lambda expressions Unrestricted unions A constructor for the union must be manually defined: union U { double f; Widget w; U(int x) : w(x) { } }; U u(3); 11 R
  • 33. Usability enhancements Type deduction Move semantics Lambda expressions Strongly typed enumerations C++03 enumerations are not type-safe. It allows the comparison between two enum values of different enumeration types. Type-safe enumeration: enum class Enum1 { Val1 = 100, Val2 // = 101 }; Override the default underlying type: enum class Enum2 : unsigned long {Val1, Val2}; Other examples: enum Enum3; // Underlying type cannot be determined (C++03/11) enum class Enum4; // Underlying type is int (C++11) 11
  • 34. Usability enhancements Type deduction Move semantics Lambda expressions Template type deduction for classes Template class: template<typename T> // "typename" and "class" are synonymous class Stack { std::vector<T> elems_; public: void push(const T& elem) { elems_.push_back(elem); } T top() const { return elems_.back(); } void pop() { elems_.pop_back(); } }; Stack<double> myStack; // T = double Stack<int*> myStack; // T = int* One Stack code for double and another Stack code for int*.
  • 35. Usability enhancements Type deduction Move semantics Lambda expressions Template type deduction for functions template <typename T> inline T max(T a, T b) { return a > b ? a : b; } std::cout << max(3.0, 7.2) << std::endl; // T = double std::cout << max("hello", "world") << std::endl; struct Widget { int x_; Widget(int x) : x_(x) { } }; Widget w1(3), w2(4); std::cout << max(w1, w2) << std::endl; // error: invalid operands to binary expression
  • 36. Usability enhancements Type deduction Move semantics Lambda expressions Template partial specialization for loop unrolling The template may also be a value instead of a class, allowing e.g. for compile-time loop unrolling, with partial specialization: template <unsigned int N> int factorial() { return N * factorial<N - 1>(); } template <> int factorial<0>() { return 1; } std::cout << factorial<4>() << std::endl; // yields 24 Since C++11, the same can be performed with constexpr. R 11
  • 37. Usability enhancements Type deduction Move semantics Lambda expressions auto for variable type deduction std::vector<int> vec{10, 11, 12, 13}; for(auto it = vec.cbegin(); it != vec.cend(); ++it) { std::cout << *it << std::endl; } 11
  • 38. Usability enhancements Type deduction Move semantics Lambda expressions decltype for return type deduction template<typename T, typename U> SomeType mul(T x, U y) { return x*y; } The return type is“the type of x*y”. How can we write that? template<typename T, typename U> decltype(x*y) mul(T x, U y) { return x*y; } It does not compile because x and y are not in scope. We can use a trailing return type. 11
  • 39. Usability enhancements Type deduction Move semantics Lambda expressions decltype for return type deduction Trailing return type: template<typename T, typename U> auto mul(T x, U y) -> decltype(x*y) { return x*y; } When decltype is read, x and y are now known to the compiler. auto is only meant to tell the compiler that it will find the return type after ->. auto does not deduce anything. 11
  • 40. Usability enhancements Type deduction Move semantics Lambda expressions Generalized return type deduction Since C++14, auto can deduce the return type of functions: auto floor(double x) { return static_cast<int>(x); } Multiple returns are allowed, but the type must be the same: auto f() { while(something()) { if(expr) { return foo() * 42; } } return bar.baz(); } 14
  • 41. Usability enhancements Type deduction Move semantics Lambda expressions Generalized return type deduction The return type deduction also works for recursive functions, provided the non-recursive return statement is before the recursive call. auto f() { return f(); } // error: return type of f is unknown auto sum(int i) { if (i == 1) return i; // return type deduced to int else return sum(i-1)+i; // ok to call it now } 14
  • 42. Usability enhancements Type deduction Move semantics Lambda expressions decltype(auto) auto always deduces a non-reference type (int, double. . . ). auto& always deduces a reference type (int&, double&. . . ). But auto cannot conditionnaly see if the return type is a reference. decltype can, but requires to write an expression in its parentheses. We can use the best of both worlds with decltype(auto) which can deduce if the type is a reference. template<typename T, typename U> decltype(auto) mul(T x, U y) { return x*y; } 14
  • 43. Usability enhancements Type deduction Move semantics Lambda expressions Copy-and-swap idiom class Array { int* arr_; unsigned int size_; public: Array(unsigned int size = 0) : size_(size), arr_(size > 0 ? new int[size]() : nullptr) { } Array(const Array& other) : size_(other.size_), arr_(other.size_ > 0 ? new int[other.size_] : nullptr) { std::copy(other.arr_, other.arr_ + size_, arr_); } ~Array() { delete[] arr_; } };
  • 44. Usability enhancements Type deduction Move semantics Lambda expressions Copy-and-swap idiom Na¨ıve implementation of operator=: Array& operator=(const Array& other) { if (this != &other) { delete [] arr_; arr_ = nullptr; arrSize_ = other.arrSize_; arr_ = arrSize_ ? new int[arrSize_] : nullptr; std::copy(other.arr_, other.arr_ + arrSize_, arr_); } return *this; }
  • 45. Usability enhancements Type deduction Move semantics Lambda expressions Copy-and-swap idiom Issues: 1 code duplication; 2 if(this != &other) mandatory but should not occur; 3 if new[] fails, *this will have been modified (no strong exception guarantee).
  • 46. Usability enhancements Type deduction Move semantics Lambda expressions Copy-and-swap idiom Successful solution: friend void swap(Array& first, Array& second) { using std::swap; // enable ADL swap(first.size_, second.size_); swap(first.arr_, second.arr_); } Array& operator=(Array other) { swap( *this, other ); return *this; } Array getArray(unsigned int size) { return Array(size); } Array arr = getArray(4);
  • 47. Usability enhancements Type deduction Move semantics Lambda expressions Copy Elisions, Returned Value Optimization Distinguish parameter and argument: other is the parameter of the function; the array returned by getArray(4) is the argument, from which the parameter other is instanciated. If the argument is a temporary object which will be destroyed, why make a copy for other? The argument should become other, thereby avoiding copy. Most C++03 compilers could grasp this optimization opportunity whenever possible and elude the copy. Guideline: Do not copy the function arguments. Instead, pass them by value and let the compiler manage the copying.
  • 48. Usability enhancements Type deduction Move semantics Lambda expressions Lvalue – Rvalue C++11 formalized everything: a temporary object, eligible for copy elision, is an rvalue; otherwise it is an lvalue. References: an integer lvalue-reference is denoted int&; an integer rvalue-reference is denoted int&&. 11
  • 49. Usability enhancements Type deduction Move semantics Lambda expressions Move constructor and move assignment operator There are two new special member functions. Move constructor: Array(Array&& other) : Array() { swap( *this, other ); } Move assignment operator: Array& operator=(Array&& other) { swap( *this, other ); return *this; } 11
  • 50. Usability enhancements Type deduction Move semantics Lambda expressions Specialize code for lvalue or rvalue void f(int& param) { std::cout << "lvalue" << std::endl; } void f(int&& param) { std::cout << "rvalue" << std::endl; } int a; f(a); // calls void f(int&) f(std::move(a)); // calls void f(int&&) If you can take a variable’s address, it usually is an lvalue. Otherwise it is usually an rvalue. 11
  • 51. Usability enhancements Type deduction Move semantics Lambda expressions std::move std::move does not move anything. It casts its parameter as an rvalue. struct Widget { Array arr_; Widget(const Array& param) : arr_(std::move(param)) { } }; Array arr(3); Widget w(arr); compiles but calls the copy constructor of Array instead of the move constructor. std::move returns a const Array&& which cannot be casted as a non-const Array&&, but can be casted as a const Array&. Array(const Array& other); // copy constructor Array(Array&& other); // move constructor 11
  • 52. Usability enhancements Type deduction Move semantics Lambda expressions Distinguish forwarding from rvalue references A forwarding reference is either an lvalue reference or an rvalue reference. A forwarding reference has the same syntax as an rvalue reference, namely “&&”. Rvalue references examples: void f(Widget&& param); Widget&& w1 = Widget(); Forwarding references: template<typename T> void f(T&& param); auto&& w2 = w1; 11
  • 53. Usability enhancements Type deduction Move semantics Lambda expressions Distinguish forwarding from rvalue references Both forwarding references have in common the presence of type deduction. Rvalue references do not. template<typename T> void f(T&& param) { // Here we can take param’s address // so param is always an lvalue } Widget w; f(w); // param’s type is lvalue-reference Widget& // param is lvalue // T = Widget& f(std::move(w)); // param’s type is rvalue-reference Widget&& // param is lvalue // T = Widget 11
  • 54. Usability enhancements Type deduction Move semantics Lambda expressions std::forward void process(Widget& lValArg); // for lvalues void process(Widget&& rValArg); // for rvalues template<typename T> void logAndProcess(T&& param) { auto now = std::chrono::system_clock::now(); makeLogEntry("Calling ’process’", now); process(param); // always calls process(Widget&) } Widget w; logAndProcess(w); logAndProcess(std::move(w)); Because param is always an lvalue, process(Widget&) is always called. 11
  • 55. Usability enhancements Type deduction Move semantics Lambda expressions std::forward If param’s type is an rvalue-reference, we need to cast the lvalue param as an rvalue. This is what std::forward does. std::move always casts as an rvalue; std::forward conditionally casts as an rvalue. But how to distinguish? Look at T: 1 if param is an lvalue-reference, T = Widget&; 2 if param is an rvalue-reference, T = Widget. T must be given to std::forward so it can decide whether to cast its parameter as an rvalue or not. process(std::forward<T>(param)); 11
  • 56. Usability enhancements Type deduction Move semantics Lambda expressions Subtle forwarding and rvalue references template<typename T> class vector { public: void push_back(T&& x); }; is not a forwarding reference. Writing std::vector<Widget> v; causes the template to be instanciated as class vector<Widget> { public: void push_back(Widget&& x); }; which involves no type deduction. 11 R
  • 57. Usability enhancements Type deduction Move semantics Lambda expressions Subtle forwarding and rvalue references A template forwarding reference must have the form T&&. Hence, the two following references do not qualify for being forwarding references. template<typename T> void f(const T&& param); template<typename T> void f(std::vector<T>&& param); 11 R
  • 58. Usability enhancements Type deduction Move semantics Lambda expressions Subtle forwarding and rvalue references The variadic templates of emplace involve type deduction. template<typename T> class vector { public: template<typename... Args> void emplace(Args&& args); }; 11 R
  • 59. Usability enhancements Type deduction Move semantics Lambda expressions Implementation of std::move in C++11 template<typename T> typename remove_reference<T>::type&& move(T&& param) { using ReturnType = typename remove_reference<T>::type&&; return static_cast<ReturnType>(param); } param is a forwarding reference: if param is an lvalue-reference, T = Widget&; if param is an rvalue-reference, T = Widget. Steps: 1 remove_reference<T>::type returns Widget; 2 remove_reference<T>::type&& returns Widget&&; 3 static_cast<Widget&&> casts param as an rvalue. 11 R
  • 60. Usability enhancements Type deduction Move semantics Lambda expressions Implementation of std::move in C++14 std::remove_reference_t<T> replaces typename remove_reference<T>::type. std::move can elegantly be written as template<typename T> decltype(auto) move(T&& param) { using ReturnType = remove_reference_t<T>&&; return static_cast<ReturnType>(param); } 14 R
  • 61. Usability enhancements Type deduction Move semantics Lambda expressions Lambda expressions auto lambda = [](int x, int y) -> int { return x + y; }; std::cout << lambda(2, 3) << std::endl; Components: (int x, int y) is the parameters list; int after -> is the return type; {...} is the lambda body. A lambda can be executed upon declaration with trailing“()”: std::cout << [](int x, int y) -> int { return x + y; }(2, 3) << std::endl; 11
  • 62. Usability enhancements Type deduction Move semantics Lambda expressions std::for each and std::transform Apply a lambda to each element of an iterator: void f(std::vector<int>& v) { std::for_each(v.begin(), v.end(), [](int p) { std::cout << p << std::endl; }); } Modify each element with a lambda: void f(std::vector<double>& v) { std::transform(v.begin(), v.end(), v.begin(), [](double d) { return d < 0.00001 ? 0 : d; }); } C++03 already had std::for_each and std::transform, but cumbersome functors were necessary since lambdas were not available. 11
  • 63. Usability enhancements Type deduction Move semantics Lambda expressions std::for each and std::transform If the body is not a single return expression, the type has to be explicitely stated: void f(std::vector<double>& v) { std::transform(v.begin(), v.end(), v.begin(), [](double d) -> double { if (d < 0.0001) return 0; else return d; }); } 11
  • 64. Usability enhancements Type deduction Move semantics Lambda expressions Lambda captures [] allows to capture other variables from the scope. void f(std::vector<double>& v, double epsilon) { std::transform(v.begin(), v.end(), v.begin(), [epsilon](double d) -> double { if (d < epsilon) return 0; else return d; }); } We can capture by both reference and value. 11
  • 65. Usability enhancements Type deduction Move semantics Lambda expressions Generalized lambda captures An element of the capture can be initialized with =. This allows renaming of variables and to capture by moving. int x = 4; auto y = [&r = x, x = x+1]() -> int { r += 2; return x+2; }(); // Updates ::x to 6, and initializes y to 7 std::unique_ptr<int> ptr(new int(10)); auto lambda = [value = std::move(ptr)] { return *value; }; std::unique_ptr can be moved but not copied. Capture by move is the only way to capture a std::unique_ptr. 14
  • 66. Usability enhancements Type deduction Move semantics Lambda expressions Generic lambdas Lambda function parameters may be declared auto. auto lambda = [](auto x, auto y) { return x + y; }; 14
  • 67. Usability enhancements Type deduction Move semantics Lambda expressions Improved return type deduction C++14 allows deduced return types for every function, not only those of the form return expression. void f(std::vector<double>& v, double epsilon) { std::transform(v.begin(), v.end(), v.begin(), [epsilon](auto d) { if (d < epsilon) return 0; else return d; }); } 14
  • 68. Usability enhancements Type deduction Move semantics Lambda expressions Remaining modern C++ topics type traits (std::enable if, std::is pointer. . . ); smart pointers; threading facilities; noexcept; std::function; std::bind and std::ref; std::regex; extern template; inline namespace. . .