Escolar Documentos
Profissional Documentos
Cultura Documentos
9/9/2014
An Overview of C++11/14
Leor Zolman
BD Software
www.bdsoft.com
leor@bdsoft.com
September 8th,2014
Agenda
C++ timeline
Goals for the new C++
Part I. Simpler language changes
Part II. New facilities for class design
Part III. Larger new language features
Initialization-related improvements
Rvalue references, move semantics and perfect
forwarding
Lambdas
An Overview of C++11/14
9/9/2014
An Overview of C++11/14
9/9/2014
An Overview of C++11/14
9/9/2014
Part I:
The Simpler Core Language Features
An Overview of C++11/14
9/9/2014
== vpi.end())
<< "no null pointers in vpi" << endl;
}
}
10
An Overview of C++11/14
9/9/2014
product of two
11
decltype and
Trailing Return Type
In this case, a combination of auto,
decltype and trailing return type provide
the only solution for C++11:
// Function template to return
// values of unknown types:
product of two
12
An Overview of C++11/14
9/9/2014
findNull in C++11
(First Cut)
Non-Member begin/end
New forms of begin() and end() even work for
native arrays, hence are more generalized
bool strLenGT4(const char *s) { return strlen(s) > 4; }
int main()
{
// Applied to STL container:
vector<int> v {-5, -19, 3, 10, 15, 20, 100};
auto first3 = find(begin(v), end(v), 3);
if (first3 != end(v))
cout << "First 3 in v = " << *first3 << endl;
// Applied to native array:
const char *names[] {"Huey", "Dewey", "Louie"};
auto firstGT4 = find_if( begin(names), end(names),
strLenGT4);
if (firstGT4 != end(names))
cout << "First long name: " << *firstGT4 << endl;
}
14
An Overview of C++11/14
9/9/2014
Non-Member begin/end
Variations in C++14
Return const_iterators:
cbegin/cend
Return reverse_iterators:
rbegin/rend
Return const_reverse_iterators:
crbegin/crend
template <typename Container>
void process_container(Container &c)
// Note: no const
{
typename C::const_iterator ci = begin(c); // C++11
auto ci2 = cbegin(c);
// C++14
. . .
}
15
16
An Overview of C++11/14
9/9/2014
nullptr
Using nullptr instead of 0 disambiguates:
void f(long) { cout << "f(long)\n"; }
void f(char *) { cout << "f(char *)\n";}
int main()
{
f(0L);
f(nullptr);
f(0);
}
17
findNull in C++11
(Final C++11 version)
template<typename Cont>
auto findNull(const Cont &c) ->
decltype(begin(c))
{
auto it = begin(c);
for (; it != end(c); ++it)
if (*it == nullptr)
break;
return it;
}
18
An Overview of C++11/14
9/9/2014
19
C++14:
auto vs. decltype(auto)
There are actually two approaches to
function return type deduction in C++14
Functions declared to return auto (or
decorated auto)
Employs template type deduction rules
Discards references, const, volatile from return
expressions type (may add it back when auto is decorated)
20
An Overview of C++11/14
9/9/2014
21
Improvement:
Range-Based for Loop
int main()
{
int ai[] { 10, 20, 100, 200, -500, 999, 333 };
for (auto i : ai)
cout << i << " ";
cout << endl;
22
An Overview of C++11/14
9/9/2014
Compile-Time Assertions:
static_assert
The C library contributed the venerable assert
macro for expressing run-time invariants:
int *pi = ;
assert (pi != NULL);
C++11 provides direct language support for compiletime invariant validation and diagnosis:
static_assert(condition, message);
Conditions may only be formulated from constant
(compile-time determined) expressions
24
An Overview of C++11/14
9/9/2014
static_assert
static_assert(sizeof(int) >= 4,
This app requires ints to be at least 32 bits.");
template<typename R, typename E>
R safe_cast(const E &e)
{
static_assert(sizeof (R) >= sizeof(E),
Possibly unsafe cast attempt.");
return static_cast<R>(e);
}
int main()
{
long lval = 50;
int ival = safe_cast<int>(lval);
25
26
An Overview of C++11/14
9/9/2014
28
An Overview of C++11/14
9/9/2014
Problem:
Dynamic Exception Specifications
In Java, all exception specifications are enforced
Old C++ functions specify exceptions they might
throw via dynamic exception specifications...but callers
need not acknowledge them!
Plus, how can function templates possibly know
what exceptions might be thrown?
Thus the only dynamic exception specification used
in the Old C++ standard library is the empty one:
template<typename T>
class MyContainer {
public:
29
30
An Overview of C++11/14
9/9/2014
Conditional noexcept
noexcept clauses can be conditional on
the noexcept status of sub-operations
// From the g++ standard librarys implementation
// of std::pair (simplified):
template<class T1, class T2>
class pair
{
// Defines data members first, second, etc.
void swap(pair& __p)
noexcept(noexcept(swap(first, __p.first))
&& noexcept(swap(second, __p.second)))
{
using std::swap;
swap(first, __p.first);
swap(second, __p.second);
}
}
31
An Overview of C++11/14
9/9/2014
Variadic Templates
// To get an average, we 1st need a way to get a sum
template<typename T> // ordinary function template
T sum(T n)
// for the terminal case
{
return n;
}
// variadic function template:
template<typename T, typename... Args>
T sum(T n, Args... rest)
// parameter packs
{
return n + sum(rest...);
}
int main() {
cout << sum(1,2,3,4,5,6,7);
cout << sum(3.14, 2.718, 2.23606);
};
33
An Overview of C++11/14
9/9/2014
An Overview of C++11/14
9/9/2014
constexpr
Enables compile-time evaluation of functions
(including operators and constructors) when
expressed in terms of constant expressions
const int SIZE = 100;
template<typename T>
constexpr T square(const T&x)
{
return x * x;
}
// simple constant
Widget warray[SIZE];
Widget warray2[square(SIZE)];
// OK, as always
// OK (compile-time)
An Overview of C++11/14
9/9/2014
No loops
Template Alias
The template typedef idea, w/clearer syntax:
template<typename T>
using setGT = std::set<T, std::greater<T>>;
// Old way
// New way
40
An Overview of C++11/14
9/9/2014
Inline Namespaces
Facilitates versioning
Names in an inline sub-namespace are implicitly
hoisted into the enclosing (parent) namespace
namespace bdsoft {
namespace v1_0
// Old version
{ }
inline namespace v2_0
// Current/default version
{
An Overview of C++11/14
9/9/2014
Attributes
Replaces #pragmas, __attribute__,
__declspec, etc.
E.g., [[noreturn]] to help compilers
detect errors
New in C++14: [[deprecated]]
Compiler issues warning if labeled entity used
Can be used for: functions, classes, typedefs,
enums, variables, non-static data members and
template complete specializations
43
long long
64-bit (at least) ints
alignas / alignof
Query/ force boundary alignment
44
An Overview of C++11/14
9/9/2014
Generalized PODs
E.g., Standard Layout Types (PODs) can
now have constructors
C++98 POD types are now subdivided into:
PODs, trivially copyable types, trivial types
and standard-layout types
45
User-defined Literals
Classes can define literal operators to convert
from literals with a special suffix into objects
of the class type, e.g.,
Binary b = 11010101001011b;
46
An Overview of C++11/14
9/9/2014
47
Part II:
Features Supporting Better Class
Design
An Overview of C++11/14
9/9/2014
class RHC
// some resource-hogging class
{
private:
RHC(const RHC &);
RHC &operator=(const RHC &);
};
//
//
//
//
Fine
Fine
Error!
Error!
50
An Overview of C++11/14
9/9/2014
//
//
//
//
//
Fine (direct)
Fine (conversion)
ERROR
ERROR
ERROR (!)
51
51
An Overview of C++11/14
9/9/2014
override / final
C++11 (mostly) lets you say what you really mean:
class Base {
public:
virtual void f(int);
virtual void ff(int);
virtual int g() const;
void h(int); // final
};
// Unfortunately, cant
// use on a non-virtual fn
//
//
//
//
//
53
final Classes
An entire class can be declared final:
class Base {};
// Derived is final
// ERROR!
54
An Overview of C++11/14
9/9/2014
55
An Overview of C++11/14
9/9/2014
private:
int id;
complex<double> capacity = 100; // ERROR!
static int nextId = 0;
// ERROR!
Cell FluxCells[num_cells];
// OK
57
};
private:
int id;
complex<double> capacity = 100;
static int nextId = 0;
Cell FluxCells[num_cells];
};
// still OK
// capacity c
// capacity 100
// Now OK!
// Still illegal
// Still OK
58
An Overview of C++11/14
9/9/2014
Inheriting Constructors
C++11 derived classes may inherit most ctors
(just not the default ctor) from their base class(es):
Simply extends the old using Base::name syntax to
ctors (arbitrarily excluded in C++98)
New ctors may still be added
Inherited ones may be redefined
An Overview of C++11/14
9/9/2014
Part III:
Larger Language Features
Initialization
Initializer lists
Uniform initialization
Prevention of narrowing
Lambdas
Rvalue references, move semantics,
universal references and perfect
forwarding (theyre all related)
61
62
An Overview of C++11/14
9/9/2014
Initializer Lists
C++11s std::initializer_list supports
generalized initialization of aggregates
It extends Old C++s array/object initialization
syntax to any user-defined type
vector<int> v = { 5, 29, 37 };
vector<int> v2 { 5, 29, 37 };
// Fine in C++11...
// Dont even need the =
template<typename T>
class vector {
// A peek inside a typical STL
public:
// containers implementation
vector(std::initializer_list<T>);
// (simplified)
vector &operator=(std::initializer_list<T>);
63
// note: foo()
// returns vector
64
An Overview of C++11/14
9/9/2014
// Unambiguous: v gets
// 10 elements each
// equal to 20
// what IS that?
int i(5.5);
double x = 10e19;
int j(x);
// legal, unfortunately
// even if impossible!
}
66
An Overview of C++11/14
9/9/2014
//
//
//
//
//
//
//
OK everywhere
OK in C++11
Error everywhere
ERROR in C++11...
but OK in Old C++!
ERROR in C++11,
OK in Old C++
68
An Overview of C++11/14
9/9/2014
69
An Overview of C++11/14
9/9/2014
71
Lambda Expressions
A lambda expression specifies an anonymous, ondemand function object
Allows the logic to be truly localized
Herb Sutter says: Lambdas make the existing STL
algorithms roughly 100x more usable.
int main()
{
vector<int> v {-5, -19, 3, 10, 15, 20, 100};
auto firstPos = find_if(begin(v), end(v),
[](int n){return n > 0;} );
if (firstPos != end(v))
cout << "First positive value in v is: "
<< *firstPos << endl;
}
72
An Overview of C++11/14
9/9/2014
73
An Overview of C++11/14
9/9/2014
An Overview of C++11/14
9/9/2014
// Output: Yes!
77
78
An Overview of C++11/14
9/9/2014
// expensive to copy
Big bt = makeBig();
Big x(), y();
Big sum = x + y;
80
An Overview of C++11/14
9/9/2014
Rvalues
Things you cant take the address of
Usually they have no name
E.g., literal constants, temporaries of various kinds
82
An Overview of C++11/14
9/9/2014
//
//
//
//
//
// copy ctor
// copy assign.
T::T(T &&);
T &operator=(T &&);
// move ctor
// move assignment
An Overview of C++11/14
9/9/2014
// 1. default ctor
// 2. destructor
// (non-canonical)
a = makeBig();
Big b(x + y);
a = x + y;
a = munge(x + y);
std::swap(x,y);
//
//
//
//
//
1
1
1
2
0
Big created *
Big created *
Big created *
Bigs created *
Bigs created!
}
// *: Return values contents moved to destination obj
86
An Overview of C++11/14
9/9/2014
Move Operations:
Not Always Automatic
Consider the Old C++-style implementation
of the std::swap function template:
template<typename T>
void swap(T &x, T &y)
// lvalue refs
{
T tmp(x);
// copy ctor
x = y;
// copy assignment
y = tmp;
// copy assignment
}
An Overview of C++11/14
9/9/2014
Big(Big &&rhs) :
b(move(rhs.b)), x(rhs.x) {}
// move ctor
Blob(Blob &&rhs) {
raw_ptr = rhs.raw_ptr;
rhs.raw_ptr = nullptr;
}
Blob &operator=(Blob &&rhs) {
if (this != &rhs) {
delete [] raw_ptr;
raw_ptr = rhs.raw_ptr;
rhs.raw_ptr = nullptr;
}
return *this;
}
private:
char *raw_ptr;
};
// move ctor
// steal pointer
// clear source
// move assign. Op
// steal pointer
// clear source
90
An Overview of C++11/14
9/9/2014
// x is an rvalue
double pi = 3.14;
auto &&y = pi;
// y is an lvalue
template<typename T>
void f(T &&val);
f(3.14);
f(x);
f(pi);
//
//
//
//
functions instantiated:
f(double &&);
f(double &&);
91
f(double &);
T
T
T
T
& &
&& &
& &&
&& &&
T&
T&
T&
T&&
Lvalue references
are infectious
-STL
template<typename t>
void f(T &&val);
double pi = 3.14;
f(3.14);
f(pi);
92
An Overview of C++11/14
9/9/2014
// copy both
// move both
// copy 1st,
// move 2nd
Perfect Forwarding
Wed prefer for each parameter to be copied or
moved as per its original lvalue-ness or rvalue-ness
class Big {
public:
template<typename T1, typename
Big(T1 &&b2, T2 &&str) :
//
b(std::forward<T1>(b2), //
s(std::forward<T2>(str)) //
{}
//
T2>
Universal refs
std::forward preserves the
lvalue-ness or rvalues-ness
(and const-ness) of its arg
private:
Blob b;
string s;
};
94
An Overview of C++11/14
9/9/2014
95
The Rule of 5
The Old C++ Rule of 3 now becomes the Rule
of 5:
Good C++11 style dictates that if you declare any
copy operation, move operation or destructor
(even if only with =default or =delete), then
you should declare all 5
If you declare any of the 5, no move operations
will be generated implicitly
The copy operations are still generated if needed
Note, however: this behavior is deprecated in C++11!
96
An Overview of C++11/14
9/9/2014
Epilogue:
Is C++ Too Complicated?
This is an oft-heard complaint
But how does one measure complexity?
Pages in the language specification?
C++98 Language: 309 pp.
C++11 Language: 424 pp.
98
An Overview of C++11/14
9/9/2014
C++ Resources
For live links to resources listed here and more,
please visit my links page at BD Software:
www.bdsoft.com/links.html
isocpp.org
100
An Overview of C++11/14
9/9/2014
Overviews of C++11/14
Bjarne Stroustrups C++11 FAQ:
http://www.stroustrup.com/C++11FAQ.html
C++14 Features
C++14 and early thoughts about C++17 (Bjarne
Stroustrup):
https://parasol.tamu.edu/people/bs/
622-GP/C++14TAMU.pdf
C++14 Wiki
http://en.wikipedia.org/wiki/C++14
102
An Overview of C++11/14
9/9/2014
104
An Overview of C++11/14
9/9/2014
Multimedia Presentations
Herb Sutter
Why C++? (Herbs amazing keynote from C++ and
Beyond 2011, a few days before C++11s ratification):
channel9.msdn.com/posts/
C-and-Beyond-2011-Herb-Sutter-Why-C
Concurrency Resources
Tutorials
Book: C++ Concurrency in Action (Williams)
Tutorial article series by Williams:
Multithreading in C++0x (parts 1-8)
C++11 Concurrency Series (9 videos, Milewski)
106
An Overview of C++11/14
9/9/2014
Boost libraries
www.boost.org
An Overview of C++11/14
9/9/2014