modern c++ programming: current state and new horizons

48
Modern C++ Programming: Current State and New Horizons Saeed Amrollahi Boyouki www.saeedamrollahi.com IRAN University of Science and Technology (IUST) Department of Computer Engineering May 2014 C++

Upload: tiffany-boone

Post on 08-Jan-2018

228 views

Category:

Documents


0 download

DESCRIPTION

About me … $ who am i Shahid Beheshti university: BA in Software Engineering Azad university: MA in Software Engineering 16 years of experience in C++ programming I have never had a course on C++ I am the first and only representative of IRAN at C++ standardization committee meetings at Frankfurt (July 2009), Rapperswil (August 2010) and Hawaii (2012) and I paid everything myself.

TRANSCRIPT

Page 1: Modern C++ Programming: Current State and New Horizons

Modern C++ Programming: Current State and New HorizonsSaeed Amrollahi Boyoukiwww.saeedamrollahi.com

IRAN University of Science and Technology (IUST)

Department of Computer EngineeringMay 2014

C++

Page 2: Modern C++ Programming: Current State and New Horizons

About me …$ who am i

• I have never had a course on C++

• Shahid Beheshti university: BA in Software Engineering• Azad university: MA in Software Engineering• 16 years of experience in C++ programming

• I am the first and only representative of IRAN at C++ standardization committee meetings at Frankfurt (July 2009), Rapperswil (August 2010) and Hawaii (2012) and I paid everything myself.

Page 3: Modern C++ Programming: Current State and New Horizons

• C++ is a general-purpose programming language with a bias towards systems programming that

is a better C supports data abstraction supports object-oriented programming supports generic programming

• Many C++ design decisions have their roots in my dislike for forcing people to do things in some particular way.

- Bjarne Stroustrup

What is C++?

C++ is a multi-paradigm programming language.

C++ is a language not a complete system.

1997-2011

• It’s still very useful definition.

Page 4: Modern C++ Programming: Current State and New Horizons

What is C++?2011-

Infrastructures Software (like OSs, VMs, Embedded systems, …)

Hardware

Applications (Browsers, DBs, Graphics, Games, …)

•C++ is a light-weight abstraction programming language. The key strengths of a C++ are in the area of

Software infrastructuresResource-constrained applications

• Operating systems, Embedded systems, Networking, Compilers, Graphics, Database systems, GUIs, Telecommunications, Search engines, Trade engines, Command and control systems, Games, …

Web Services/Applications

Native code, System

programming, Library building

Page 5: Modern C++ Programming: Current State and New Horizons

C++0x roadmap

1998

2003 2011

1999

C++98

C99

C++03 C++11 C++1y

C1x

• C++0x = C++11x = B

• C++1y = C++1?probably y = 7

C

Simula

1978

1967

• 2,000,000 <= Number of C++ programmers <= 4,000,000• It’s close to 4,000,000

Living languages must change, must adapt, must grow. – Edward Finegan

2014 2017

5C++11- SRTTU

• In this seminar: C++98 = C++03

Page 6: Modern C++ Programming: Current State and New Horizons

Taste C++11C++ feels like a new language.

- Bjarne Stroustrup

•An overview on iota generic algorithm•Simple asynchronous operations•Concurrent accumulation

Page 7: Modern C++ Programming: Current State and New Horizons

7

Sequence containers population

• To fill sequence containers incrementally

vector<int> v1(100); // 100 integers with value 0vector<int> v2(100, -1); // 100 integers with value -1vector<int> v3{0, 1, 2, 3}; // C++11 initializers listvector<int> v4(100);// fill v4 with values: 0, 1, 2, … 99vector<int> v4; // empty vectorfor (vector<int>::size_type sz = 0; sz < v4.size(); ++i) { v4.push_back(sz);}// another methodfor (vector<int>::size_type sz = 0; sz < v5.size(); ++sz) { v5[sz] = sz;}

Page 8: Modern C++ Programming: Current State and New Horizons

• Requires: T shall be convertible to ForwardIterator’s value type. The expression ++val, where val has type T, shall be well formed.

• Effects: For each element referred to by the iterator i in the range [first,last), assigns *i = value and increments value as if by ++value.

• Complexity: Exactly last - first increments and assignments.

8

template <class ForwardIterator, class T>void iota(ForwardIterator first, ForwardIterator last, T value);

• iota is a new generic algorithm in C++11.• More than 30 new generic algorithms were added to C++11.

Forward Iterator

=*p -> == != ++

*p=

Input Iterator

It’s not inheritance!

• header file : <numeric>

Iota 11

Page 9: Modern C++ Programming: Current State and New Horizons

iota and fundamental types

9

// iota_practice.c++#include <numeric>#include <vector>#include <list>#include <iostream>#include <array>int main(){ using namespace std; vector<int> vi(1000000); list<double> lst(1000000); array<char, 26> lower_case; // array is new container vector<long long> vll(10); // long long is a new fundamental data type iota(vi.begin(), vi.end(), 0); // 0, 1, 2, ..., 999999 iota(lst.begin(), lst.end(), 0.0); // 0.0, 1.0, 2.0, … 999999.0 iota(lower_case.begin(), lower_case.end(), 'a'); // 'a', 'b', … 'z' iota(vll.begin(), vll.end(), 0LL); // 0LL, 1LL, 2LL, … 9LL for (auto c : lower_case) cout << c << ‘ ‘; // range-based for loop cout << ‘\n’; return 0;}

• Here it is a complete program that uses iota with fundamental types:

• C++11: array container, long long data type, range-based for loop and auto

Page 10: Modern C++ Programming: Current State and New Horizons

iota cont.

10

// under Code::Blocks 10.05 (Release mode)$ g++ -std=c++11 –pedantic –Wall –O3 iota_practice.c++ -o iota_practice$ ./iota_practicea b c d e f g h i j k l m n o p q r s t u v w x y zProcess returned 0 (0x0) execution time: 0.142 s

namespace std { template<class ForwardIterator, class TYPE_> void iota(ForwardIterator first, ForwardIterator last, TYPE_ t) { for (auto it = first; it != last; ++it, ++t) // prefix ++ *it = t; }}

• A typical/likely implementation of iota

y = ++x; // y = (x += 1) or ++x; y = x;y = x++; // y = (t = x, x += 1; t) or t = x; x++; y = t;

• Pre increment vs. Post increment

• ++x means to increment x and return the new value, while x++ is to increment x and return the old value. iota uses prefix ++ increment.

•The value of ++x, is the new (that is, incremented) value of x. The value of x++, is the old value of x.

Page 11: Modern C++ Programming: Current State and New Horizons

iota and user-defined types• Rational numbers, 2D points and SE Closing prices, …

11

// rational.hclass Rational { // non-normalized run-time rational number int numerator_, denominator_;public: Rational() : numerator_{0}, denominator_{1} {} // new initialization

// syntax // other ctor(s), relop(s), other member functions Rational& operator++() { numerator_ += denominator_; return *this; }};

1.

// point.hclass Point { // 2D point int x_, y_;public: Point() : x_{0}, y_{0} {} // ctor(s), graphics-related member functions Point& operator++() { ++x; ++y; return *this; }};

2. (0, 0)

(n-1, n-1)

Page 12: Modern C++ Programming: Current State and New Horizons

// price.hclass price_stepper { // price stepper for a typical securities exchange double price_;public: static const double STEP{0.05}; // new syntax for uniform initialization static const double FACE_VALUE{1000.00}; price_stepper() : price_{FACE_VALUE} {} // default ctor price_stepper(double price) : price_{price} {} operator double() const { return price_; } price_stepper& operator++() { price_ += STEP; return *this; }};

iota and user-defined types

12

3.

// gadget.hclass FuturisticGadget { // An Unidentified futuristic gadget: 22 centurypublic: FuturisticGadget& operator++() { /* … */ }};

4.

• Template duck typing:If it looks like a duck, walks like a duck, and quacks like a duck..., so it’s a duck.

Page 13: Modern C++ Programming: Current State and New Horizons

13

iota and user-defined data types

#include <array>#include <numeric>#include <vector>#include <list>#include <iostream>#include “point.h”#include “rational.h”#include “price.h”#include “gadget.h”

int main(){ using namespace std; array<Point> vp(10000); list<Rational> lr(100000); vector<price_stepper> p_list(100000); iota(vp.begin(), vp.end(), Point()); // [point(0, 0), point(9999, 9999)] iota(lr.begin(), lr.end(), Rational()); // [ iota(lower_case.begin(), lower_case.end(), 'a'); // 'a', 'b', .. 'z' iota(vll.begin(), vll.end(), 0LL); // 0LL, 1LL, 2LL, 9LL return 0;}

• Complete program

Page 14: Modern C++ Programming: Current State and New Horizons

C++11 Concurrent programming facilities- from top to button

Threads (Construction, Launch)

OS Threads (Windows, Posix)

future, promise, packaged_tasks

mutexes , locks and condition_variables

async

Low-level/System-level concurrency

High-level concurrency

Hardware

Task-based concurrency

Thread-based

concurrency

Page 15: Modern C++ Programming: Current State and New Horizons

Simple Async

#include <string> // for string#include <algorithm> // for reverse#include <vector> // for vector#include <future> // for async and future#include <iostream> // for cout

std::string flip(std::string s){

std::reverse(std::begin(s), std::end(s));return s;

}

int main(){

std::vector<std::future<std::string>> v; v.push_back(std::async([]{ return flip(" ,olleH"); }));

v.push_back(std::async([]{ return flip(" tnerrucnoc"); })); v.push_back(std::async([]{ return flip("\n!dlrow"); }));

for (auto& e: v)std::cout << e.get();

return 0;}

Non-member functions

begin and end

FutureRight angle

bracket

Auto initialization

98 1

1

Range-based for loop

Async

Lambdas

Page 16: Modern C++ Programming: Current State and New Horizons

Future and async

•The function template async provides a mechanism to launch a function potentially in a new thread and provides the result of the function in a future object with which it shares a shared state.

•The class template future defines a type for asynchronous return objects which do not share their shared state with other asynchronous return objects.

future

value

get member function

Async function

Returns

task

thread

Page 17: Modern C++ Programming: Current State and New Horizons

Accumulate function

template <class InputIterator, class T>T accumulate(InputIterator first, InputIterator last, T init);

98

•Effects: Computes its result by initializing the accumulator acc with the initial value init and then modifies it with acc = acc + *i for every iterator i in the range[first,last) in order. Requires: T shall meet the requirements of CopyConstructible and CopyAssignable types.• Complexity: Exactly last - first increments and assignments.

• The generic accumulate function

/* read doubles from standard input and compute the summation */vector<double> values;double x;while (cin >> x) // read until we have values.push_back(x);double sum = accumulate(values.begin(), values.end(), 0.0);

• header file : <numeric>• Example:

Page 18: Modern C++ Programming: Current State and New Horizons

Concurrent Accumulation#include <numeric>#include <vector>#include <future>

template<class T>T accum(T* begin, T* end, T init){ return std::accumulate(begin, end, init);}

template<class T, class V> struct Accum{ T *b, *e; V val; Accum(T* bb, T* ee, const V& v) : b{bb}, e{ee}, val{v} {} V operator()() const { return std::accumulate(b, e, val); } };

Page 19: Modern C++ Programming: Current State and New Horizons

Concurrent accumulationtemplate<class T>T comp(std::vector<T>& v, int size, int cc){ if (v.size() < size) // use sequential accumulate return std::accumulate(v.begin(), v.end(), 0.0); else { auto f0{std::async(Accum(v.begin(), &v[v.size()/cc], 0.0))}; auto f1{std::async(accum(&v[v.size()/cc], &v[v.size() * 2 / cc],

0.0))}; auto f2{std::async(accum(&v[v.size() * 2 / cc],

&v[v.size()*3/cc, 0.0))}; auto f3{std::async(accum(&v[v.size() * 3 / cc, v.end(), 0.0))}; return f0.get() + f1.get() + f2.get() + f3.get(); }}

int main(){ vector<double> v(100000000); iota(v.begin(), v.end(), 0.0); cout << comp(v, 10000, 4) << '\n';

return 0;}

Page 20: Modern C++ Programming: Current State and New Horizons

RAII- Resource Acquisition is Initialization

• A simple technique for handling resources in programs using exceptions. One of the keys to exception safety.

- Bjarne Stroustrup Glossary page http://www.stroustrup.com/glossary.html

• RAII is about Resource Management.• A basic technique for resource management based on scopes.

- Bjarne Stroustrup programming Principles and Practice Using C++, page 1175.

• RAII is a programming idiom or technique used for exception-safe resource management.

- Wikipedia http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

98

• Resource: any entity that a program acquires and releases.Examples: memory, file handles, thread handles, locks, sockets, timer, transactions, network connection, data base connection, …

• One of the key tasks of any non-trivial program is to manage resources. For a long-running program, failing to release a resource in a timely manner can cause serious performance degradation and possibly crash.

Page 21: Modern C++ Programming: Current State and New Horizons

ConstructorResource

Acquisition

Resource Release

Destructor

Constructors, destructors and resources

• A constructor is used to initialize objects of its class type.

• A destructor is used to destroy objects of its class type.

class X {public: X() = default; // default constructor X(const X&) = default; // copy constructor X(const X&&) = default; // move constructor X& operator=(const X&) = default; // copy assignment op. X& operator=(const X&&) = default; // move assignment op. ~X() = default; // destructor // …};

Initialization

Cleanup

class X { // the empty class};

Compiler generates

• Destroy = cleanup

Page 22: Modern C++ Programming: Current State and New Horizons

Scope-based Resource Management• A basic technique for resource management based on scopes.

- Bjarne Stroustrup programming Principles and Practice Using C++, page 1175.

class X { X(); ~X(); // …};

void f(){ X x; // constructor vecor<int> v; string s(“Hello, world”);} // calling destructor(s) at the end of scope (in reverse order)

Page 23: Modern C++ Programming: Current State and New Horizons

Resource Acquisition Is Initialization

stringvector map

other containers

lock_guard/unique_lockshared_ptr/unique_ptr threads

list

RAII and standard library abstractions

Page 24: Modern C++ Programming: Current State and New Horizons

Literals

C++data types

Fundamental types = Built-in typesUser-defined types

Fundamental types

C++98

charshort int long

float doublelong double

boolwchar_t char16_t

char32_t

long long

C++11

• literal is notation that directly specifies a value for fundamental values.

- Bjarne Stroustrup Programming- Principles an Practice Using C++, page 1174.

• Each fundamental type has set of values called literals.

// C++98 fundamental types and their literalsbool b = true; // true and false are literals for bool typechar c = ‘A’; // (narrow) character literalshort s = 42; // short intint i = 1; // 1 is integer literallong L = 1L; // the suffix L makes a long literalfloat f = 1.0f // single precision floating point literaldouble d = 1.0 // the double precision floating point literalwchar_t wch = L’A’ // (wide) character

• Example:

98

Page 25: Modern C++ Programming: Current State and New Horizons

Literals, cont.

// C++98 fundamental types and their literals, continuedint* p = 0; // 0 was pointer literalconst char* str = “hello, world”; // char. string literalconst wchar_t* ws = L”Hello, world”; // the wide char. string literal

// C++11 fundamental types and their literalslong long GE = 30000000000000; // great embezzlement in IRR:)long long big_one = 1LL; // LL makes a long long literalint* p2 = nullptr; // nullptr is pointer literalchar16_t c1 = u’h’; // 16-bit char. literalchar32_t c2 = U’h’; // 32-bit char. literalconst char16_t* s1 = u”Hello, world”; // 16-bit char. string literalconst char32_t* s2 = U”Hello, world”; // 32-bit char. string literal

• C++11 has three new fundamental types: long long, char16_t and char32_t

• Example:

11

14

// C++14 fundamental types and their literalsunsigned char a = 0b11110000; // binary literal

Page 26: Modern C++ Programming: Current State and New Horizons

<type-specifier> variable-name = initializer opt ;

bool b; // non-local variable: b = false int main(){

long long LL; // uninitializedauto long long LL; // redundant auto. rather

verboseauto std::string s; // calling default ctorreturn 0;

} //

Global variable

Local variables

Automatic storage

• In C++98, the programmer must state the type of variables.

Static languages: Fortran, Algol, C, C++, Java, …

Dynamic languages: Lisp, Python, … State the

type of variables

clearly

Deduce the type of variables with the assigning values

• Pythonanswer = 42 # answer is now an intanswer = 42.1 # answer is now a float

double g = 9.81f; // g is doubleint answer = 42.1; // answer = 42

1.

2.

• Compiler prefers type to initializer.

98

Automatic variables

Page 27: Modern C++ Programming: Current State and New Horizons

• Recycle the keyword auto:1) To remove the old redundant usage2) New responsibility: Determine or deduce the type of expressions from initializer

New mission of auto

Run-timeDesign-time Compile-time

Specify types at design-time

C/C++

Deduce types at compile-time from

initializersC/C++

Deduce types at Run-time based on

assignmentLisp/Python

• Third approach: Compiler can figure out the type of expressions at compile-time.

auto <variable> = expression

• The original auto is generally useless keyword.

int x = 5; // verbose: the int is redundantauto x = 5; // OK: x is int because 5 is int

11

Auto: type deduction from initializer

Page 28: Modern C++ Programming: Current State and New Horizons

• Initialization vs. Assignment

Using auto

auto pi = 3.14; // pi is double, because 3.14 is double (by default)auto pi_ptr = &pi; // pointer to doubleauto big_one = 1LL; // big_one is long long because LL suffixtemplate<class T> T* Factory(T t) { return new T(t); }auto clone1 = Factory(1); // clone1: int*auto clone2 = Factory(2.0f), // clone2: float*auto clone3 = Factory(complex<double>{1, 1}); // clone3: complex<double>*

• Basic examples:

auto big_one = 1LL; // initialization: big_one is long long foreverbig_one = 1UL; // assignment: big_one is still long long

// the today (opening, closing) prices of symbols at NASDAQmap<string, pair<double, double>> price;// print the content of mapfor (map<string, pair<double, double>>::iterator it = price.begin(); it != price.end(); ++it) {

cout << it->first << ‘\t’ << ‘[‘ << it->second.first << ‘,’ << it->second.second << ‘]’ << ‘\n’;

}

MSFT 27.56

DELL

28.10

15.16 15.34

ORCL 26.70 26.93

• Examples

for (auto it = price.begin(); it != price.end(); ++it) {cout << it->first << ‘\t’ << ‘[‘ << it->second.first

<< ‘,’ << it->second.second << ‘]’ << ‘\n’;}

1.

2.

Page 29: Modern C++ Programming: Current State and New Horizons

Range-based for loop• Conventional general for statement: You can do almost anything.

for (initialization-statement condition opt; expression opt) statement

int a[10];for (int i = 0; i <=10; ++i) { a[i] = 0;}

void print(list<int>& L){ for (list<int>::const_iterator cit = L.begin(); cit != L.end(); ++cit)

cout << *cit << ‘\n’; }

void print(list<int>& L){

ostream_iterator<int> os(cout, “\n”);

copy(L.begin(), L.end(), os); }

• off-by one error

• Rather verbose

• Looks like difficult

1.

2.

• Common idiom in C++ programming: Iterator through a container from begin to end

Page 30: Modern C++ Programming: Current State and New Horizons

Lambda expressions• Lambda expressions provide a concise way to create

simple function objects.• Lambda expressions = Lambda functions = Lambdas

[ Captures opt ] ( Parameters opt ) -> Return Type opt { Statements; }

Lambda introducer

#include <iostream>#include <vector>#include <algorithm>using namespace std;vector<int> v = {-10, -7, -3, 0, 1, 4, 9, 10, 20, 31, 40, 41, 45, 64, 99};int main(){ auto cit = find_if(v.begin(), v.end(), [](int n) { return n > 0; }); if (cit != v.end()) cout << *cit << ‘\n’; // 1 return 0;

• C++11: Modern style code: 2008-

11

Page 31: Modern C++ Programming: Current State and New Horizons

Constants• C++ has always had the concept of constant expressions from 1985

const double PI = 3.14159; // don’t change the content of PIchar* hi = “Hello, world”; // “Hello, world” is constant character literalconst char* hi = “Hi”; // pointer to constant datachar* const hello = “Hello”; // constant pointer to characterconst char* const Hawaii = “Aloha”; // constant pointer to constant characterclass Point {

int x, y;const int z; // constant data member

public:Point(int xx, int yy) : x(xx), y(yy), z(0) {}int GetX() const { return x; } // constant member functionint GetY() const { return y; }void SetX(int xx) { x = xx; } // non-constant member function

};const Point Center(0, 0); // constant objectvoid f(const Point); // copy semantics: don’t change the content of argumentvoid g(const Point&); // reference semantic: don’t change the// more …

• const’s primary function is to express the idea that an object is not modified through an interface.• constant advantages: Excellent optimization opportunities for compilers, more maintainable code.

Page 32: Modern C++ Programming: Current State and New Horizons

Conventional constants- problems•The constant expressions may be or may be not evaluated at compile-

time.

// array_bound.c++int get_five() { return 5; }long long LA[get_five() + 10]; // error: array bound is not an integer constant

• Example: array bound

$ g++ -c -std=c++98 array_bound.c++error: array bound is not an integer constant

1.

• The problem is from the point of theoretical view, get_five() isn’t constant expression.

• Embedded system programming: Read-Only Memory (ROM)

const double PI = 3.14159;const double GRAVITY_CONSTANT = 9.81; // m/s2const int FACE_VALUE = 1000; // the face value of each share at TSE (in IRR)

Page 33: Modern C++ Programming: Current State and New Horizons

• I mean, generalized and guaranteed constant expressions.Constant expressions

• Generalized and guaranteed constant expressions (constexpr) extends compile time evaluation to variables of fundamental types as well as variables of user-defined types and functions.

2.

// array_bound.c++#include <iterator> // for std::begin and end#include <algorithm> // for std::fillconstexpr int get_five() { return 5; }long long LA[get_five() + 10]; // OKstd::fill(std::begin(LA), std::end(LA), 42LL);

$ g++ -c -std=c++11 array_bound.c++$

The constexpr mechanism • Provides more general constant expressions

• Allows constant expressions involving user-defined types ROM• Provides a way to guarantee that an initialization is done at compile

time.

• constexpr is a new keyword in C++11. constexpr is kind of specifier.

11

Page 34: Modern C++ Programming: Current State and New Horizons

• both const and constexpr are mechanisms to specify immutability. const vs. constant expressions

const int i = 0;constexpr int ii = 0;void f(){

++i; // error: increment of read-only variable ‘i’

++ii; // error: increment of read-only variable ‘i’}• const is meaning roughly: I promise not to change this value.

• constexpr is meaning roughly: to be evaluated at compile time.

Evaluate at compile time

Do not modify in this scope

constexprconst

• const: conventional constants• constexpr: generalized and guaranteed compile-time evaluation constants

Page 35: Modern C++ Programming: Current State and New Horizons

C-style pointers problems1. Pointers don’t have the value semantic.

2. Pointers don’t have ownership management.

int i = 0;int j = i; // copyj = i; // assignmentstring s = “A string …”;string t = s; // another stringstring u;u = t; // copy assignment op.

• int and std::string are perfect examples of types with value semantics.

char* p = “No value semantics”;char* q = p; // p and q point to single datalong long* llp = new long long(3000000000000);long long* llp2 = llp;delete llp;delete llp2; // double deletion catastrophic

42

int* ip = new int(42); // 1: ip owns the allocated memory// …ip = 0; // 2: assign something else to p: lose ownership

//1

//2ip

ip

• the variable ip not only points to, but also owns, the memory allocated for the integer object.

Memory leak

• Shallow copy vs. Deep copy

Page 36: Modern C++ Programming: Current State and New Horizons

C-Style pointers problems cont.

3. The problem about “automatic” memory management.• new and delete• new [] and delete []

class MyClass {// …

};

void f(){

MyClass* p = new MyClass(); // memory allocationMyClass* pa = new MyClass[10];// …delete p; // memory releasedelete [] pa;

}4. No exception safety

X* f(){ X* p = new X; // do something // maybe throw an exception: memory leak return p;}

• Exception-safety: the notion that a program is structured so that throwing an exception doesn't cause unintended side effects.

• typical side-effect: Memory leak• RAII: Resource Acquisition is

Initialization

Page 37: Modern C++ Programming: Current State and New Horizons

Smart pointers: definitions•A smart pointer is a C++ class that mimics a regular pointer in syntax

and some semantics, but it does more.

p 42

• Solution: Put raw pointers in a class and try to mimic their behaviors.

11

pp

p 42

42pp

Page 38: Modern C++ Programming: Current State and New Horizons

Raw pointers vs. smart pointers• C-Style pointers Raw pointers • Solution: Put raw pointers in a

class and try to mimic their behaviors.

• C++98: auto_ptr

// abbreviated and simplifiedtemplate<class T> class std::auto_ptr {private:

T* p;public:

explicit auto_ptr(T* p_ = 0) : p(p_) {}auto_ptr& operator=(const auto_ptr& ap){

p = ap.p; ap.p = 0; return *this;}auto_ptr(auto_ptr& ap) :

p(ap.p) { ap.p = 0; }~auto_ptr() { delete p; }T& operator*() const { return *p; }T* operator->() const { return p; }

private:T* p;

};

1.

void client(){

auto_ptr<float>ap(new float(3.14)); // 1

// use apfloat f= *ap;

auto_ptr<float> ap2 = ap; // 2// no need to delete auto ptrs

} // ap2 and ap are destroyed here

2.

3.14

//1

//2apap2

3.14p

p

ap p

Transfer ownership

Page 39: Modern C++ Programming: Current State and New Horizons

• Almost every nontrivial applications controls some resource whose life-time is intermediate between the lifetime of an auto object, which exists only while the function that defines it is executing, and the lifetime of a global object, which exists as long as the program is running.

Pete Becker. The C++ Standard Library Extensions: A Tutorial and Reference. Addison-Wesley, 2005.

int g; // non-local (global) object, zero initializationvoid f(){

int i = 0;int* ip = new int{0};// …delete ip;

} // release the memory allocated for i at the end of scope

• resource: memory, timer, network connection, database connection, lock, timer, …

Resource management

Page 40: Modern C++ Programming: Current State and New Horizons

Unique_ptr vs. C-Style pointers: Performance comparison

{ int* ip = new int{0}; // … delete ip;}

#include <memory>{ int* up = std::unique_ptr<int>{new int{0}}; // …}

Page 41: Modern C++ Programming: Current State and New Horizons

Smart pointers in C++11 C++11

• unique_ptr: Strict ownership• shared_ptr: Shared ownership• weak_ptr: Shared ownership

template<class T> class shared_ptr { T* p; long use_count;};void test(){ shared_ptr<int> p1(new int(42)); // count is 1 { shared_ptr<int> p2(p1); // count is 2 { shared_ptr<int> p3(p1); // count is 3 shared_ptr<int> p4; p4 = p3; // count is 4 cout << p1.use_count() << '\n'; // print 4 cout << (*p1) << '\n'; // print 42 // count goes back down to 2 } } // count goes back down to 1} // here the count goes to 0 and the int is deleted.

Page 42: Modern C++ Programming: Current State and New Horizons

Memory management in C++: 1985-2014

Memory management

new & delete operators

Pointer to member functions

auto_ptr

Garbage collected containers (string,

vector, list, map, …)Smart pointers

(shared_ptr, unique_ptr and

weak_ptr)

Commercial Garbage

Collectors

Programmer-controlled

garbage collectors

C++1y?

Page 43: Modern C++ Programming: Current State and New Horizons

Invitation to (re)learn C++

• I invite you to learn/re-learn C++.

• We are just at the golden era of C++.• A lot of free, standard compliance and modern

compilersGCC 4.9.0Clang 3.4Visual Studio 2012 (express edition)

Page 44: Modern C++ Programming: Current State and New Horizons

Know your discipline heroes/legendaries

44

• www.stroustrup.com- Bjarne Stroustrup. The C++ Programming Language. Addison-Wesley. 2013, 4th Edition. ISBN 978-0321563842.- Bjarne Stroustrup. Programming- Principles and Practice Using C++. Addison-Wesley. ISBN 978-0321543721. 2008.- A few other books and a lot of papers

• www.stepanovpapers.com- Alexander Stepanov and Paul McJones: Elements of

Programming. Addison-Wesley Professional, 2009.- A lot of papers

Bjarne Stroustrup (Morgan-Stanley/Columbia university/TAMU)

Alex Stepanov (A9.com)

If I have seen further it is by standing on the shoulders of giants.- Sir Isaac Newton

Page 45: Modern C++ Programming: Current State and New Horizons

Know your discipline heroes/legendaries

45

Andrew Koenig (Retired from AT&T Bell Lab)• www.drdobbs.com/cpp- Andrew Koenig and Barbara Moo. Accelerated C++: Practical Programming by Example, Addison-Wesley, 2000.- A lot of papers

Scott Meyers (Software development consultant)• www.aristeia.com- Scott Meyers. Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library. Addison-Wesley, 2001.- A lot of papers

Herb Sutter (Microsoft)• www.gotw.ca• http://herbsutter.com-Herb Sutter Exceptional C++ Style. Addison-Wesley, 2004, ISBN 0-201-76042-8.- and a few other books and a lot of papers.

Page 46: Modern C++ Programming: Current State and New Horizons

46

• http://erdani.com/Andrei Alexandrescu (Facebook)

P. J. Plauger (Dinkamware)• http://plauger.com• www.dinkumware.com

Howard Hinnant (Ripple)• www.boost.org

Matt Austern (Google)• www.lafstern.org/matt

Know your discipline heroes/legendaries

• Google discussion groups: comp.lang.c++, comp.lang.c++.moderated

-The Standard Template Library, Prentice-Hall, 2001.

- Generic Programming and the STL: Using and Extending the C++ Standard Template Library. Addison Wesley Longman, Reading, MA, 1998. - A lot of papers

- Modern C++ Design- Generic Programming and Design Patterns Applied.. Addison Wesley Longman, Reading, MA, 2001. - A lot of papers

Page 47: Modern C++ Programming: Current State and New Horizons

References and further readings

Bjarne Stroustrup. The C++ Programming Language. Addison-Wesley, Reading, MA, 2000. special edition.

International Organization for Standards. Latest publicly available ISO C++ draft http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3376.pdf

Saeed Amrollahi. Modern Programming in New Millennium: A Technical Survey on Outstanding features of C++0x. Computer Report (Gozaresh-e Computer), No.199, November 2011 (Mehr and Aban 1390), pages 60-82. (Persian)

Bjarne Stroustrup. C++11 FAQ. 2011, http://www.stroustrup.com/C++11FAQ.html Bjarne Stroustrup. The C++ Programming Language. Addison-Wesley. ISBN 978-0321563842. 4th Edition, 2013. GoingNative 2012 & 2013 conference. http://channel9.msdn.com/Events/GoingNative/GoingNative-2012.

Bjarne Stroustrup. Programming- Principles and Practice Using C++. Addison-Wesley. ISBN 978-0321543721. 2008.

The home of Standard C++ on the web — news, status and discussion about the C++ standard on all compilers and platforms.http://www.isocpp.org/

47

Page 48: Modern C++ Programming: Current State and New Horizons

Thanks for your patience …

&

Learning to ask the right (often hard) questions is an essential part of learning to think as a programmer.

- Bjarne Stroustrup programming Principles and Practice Using C++, page 4.