Introduction to Move Semantics in C++ C and C

Size: px
Start display at page:

Download "Introduction to Move Semantics in C++ C and C"

Transcription

1 Introduction to Move Semantics in C++ C and C Jean-Paul RIGAULT University of Nice - Sophia Antipolis Engineering School Computer Science Department Sophia Antipolis, France Contents of the Course Introduction: impact and definition of move semantics RValues and Lvalues; move semantics Type deduction Universal References jpr@polytech.unice.fr 1 2 Impact of Move Semantics (1) vector<double> get_vector(unsigned n) { vector<double> vec(n, 2.0); return vec; Part 1 Introduction vector<double> absorb_vector(vector<double> v) { return v; int main() { const unsigned N = ; clock_t c0 = clock(); vector<double> vec = absorb_vector(get_vector(n)); clock_t c1 = clock(); double t = double(c1 - c0)/clocks_per_sec*1000; cout << t << endl; 3 4

2 Impact of Move Semantics (2) Copy and move semantics C copy semantics no optim -O3 Compile Options g clang C C C C C C Times are in ms N = 10 8 MacOS MacBook Pro Intel Core i GHz vector<double> get_vector(unsigned n); vector<double> absorb_vector(vector<double> v); absorb_vector(getvector(n)); v vtemp 5 6 Copy and move semantics C move semantics Copy and move semantics When should we move instead of copying? vector<doble> get_vector(unsigned n); vector<double> absorb_vector(vector<double> v); absorb_vector(getvector(n)); v vtemp Situations where moving is more efficient than copying Manipulating temporary objects Passing/returning by value Reallocating (internal) memory Example: vector<t>::push_back() Objects have data on the heap Deep copy is required Moving is never less efficient than copying But, of course, moving is not always possible! 7 8

3 Copy and move semantics Another example: swap() (1) Copy and move semantics Another example: swap() (2) Traditional standard implementation of swap() template <typename T> void swap(t& a, T& b) { T tmp(a); // now 2 copies of a a = b; // now 2 copies of b b = tmp; // now 2 copies of tmp // destructor of tmp The compiler cannot/does not move automatically Fixing swap() in C template <typename T> void swap(t& a, T& b) { T tmp(std::move(a)); a = std::move(b); b = std::move(tmp); // moves a s data to tmp // moves b s data to a // moves tmp s data to b // destructor of tmp... // not much left to do The compiler cannot/does not move automatically But we can instruct it to do so 9 10 RValues and LValues Part 2 RValues and Lvalues Move Semantics How to distinguish when we can move instead of copying? C/C++ already distinguish LValue: something that has an address usually it has also a name or it is accessed by following a pointer or an Lvalue reference indeed: name LValue RValue: something that has no address typically, pure values, unnamed temporary objects int i = 4, *pi = &i; // i, pi, *pi are LValues // 4, &i are RValues vector<int> vi; // vi is LValue vi[5] = 3; // vi[5] is LValue string f(string str); // str is LValue // return of f() is RValue string s = f( hello ); // s is LValue // hello is RValue // return of f() is RValue // temporary string for // hello is RValue 11 12

4 Copying/moving RValues and LValues RValue and LValue references (1) Value movement is generally unsafe when source is an LValue the LValue object must continue to exist since it can be referred later Value movement is always safe when source is an RValue the temporary will go away at the end of statement change to temporary value will be unnoticed vector<string> vs1, vs2; vs1 = vs2; // copy, not move vs1[0] = vs2[0]; // copy, not move vs1[1] = vs2[0]; // copy, not move string f(string str); string s = f( hello ); // temporary string( hello ) // can be moved into local str // temporary string returned by // f() can be moved into s // (or RVO) string s1{ hello ; string s = f(s1); // s1 must be copied into str C++ has already LValue references (to const and non-const) T& reflv_non_const; const T& reflv_const; C introduces RValue references T&& refrv; const T&& refrv_const; RValue references have the same properties as normal (LValue) ones They must be initialized They cannot be rebound to another object RValue reference identify objects that can be safely moved from RValue and LValue references (2) RValue and LValue references (3) Important remark The type of an expression does not depend of whether the expression is an Lvalue or a Rvalue int y = 3; int x = y; // name y is a LValue // expression y is an int In particular, all functions formal parameters are Lvalues because they have a name and even if they designate (bind to) an Rvalue int f(string&& str); // str is an LValue int x = f( hello ); // here bound to a RValue Binding rules for references Usual rules (C ) for LValue references An RValue can be bound to an RValue reference An LValue cannot be bound to an RValue reference If it were possible, LValues could be accidentally modified Effective parameter LValue ref. to non const (T&) Formal parameter LValue ref. to const (const T&) RValue ref. RValue T LValue T 15 16

5 vector<int> vec; vector<int> f(); RValue references (2) void g1(const vector<int>& v); g1(vec); // OK, as before g1(f()); // OK, as before // vec is a (non const) LValue // f() returns a (non const) RValue void g2(const vector<int>& v); // #1 void g2(vector<int>&& v); // #2 g2(vec); // argument is LValue only #1 is viable g2(f()); // both viable, arg is RValue #2 better match void g3(const TVec&& v); // #1 void g3(tvec&& v); // #2 g3(vec); // ERROR, an LValue cannot bind to an RValue g3(f()); // both viable, arg is non const RValue #2 better match Copy and move special operations (1) Beside copy constructor and copy assignment operator, a class may define a move constructor and/or a move assignment operator class A { A(const A&); // copy constructor A& operator=(const A&); // copy assignment A(A&&); // move constructor A& operator=(a&&); // move assignment ; A f(); A a1; A a2 = a1; A a2 = f(); a2 = f(); a1 = a2; // function returning a RValue // copy constructor // move constructor // move assignment // copy assignment Copy and move special operations (2) Implementation of move operations class A { Data *_pdata; // Pointer to internal data A(A&& a) : _pdata(a._pdata) { // move constructor a._pdata = nullptr; A& operator=(a&& a) { // move assignment delete _pdata; _pdata = a._pdata; a._pdata = nullptr; ; Note that the source of the move must be left in valid state, so that is can be deleted Copy and move special operations (3) Bad implementation of move operations class A : public Base { string _str; A(A&& a) : Base(), _str(a._str) { A& operator=(a&& a) { Base::operator=(a); _str = a._str; ; Assume Base has copy and move operations string has copy and move operations Sources are LValues since they Sources are LValues (they have have names. Hence copy, not names), hence copy, not move move 19 20

6 Copy and move special operations (3) Fixing bad implementation of move operations class A : public Base { string _str; A(A&& a) : Base(), _str(std::move(a._str)) { A& operator=(a&& a) { Base::operator=(a); _str = std::move(a._str); ; Sources Force a are move LValues operation, (they have if names), hence available copy, not move Copy and move special operations (4) As for the Big Four, the compiler is able to synthesize missing move operations (move constructor and move assignment) A move operation is automatically generated if all the following conditions hold: no copy operation is explicitly declared the other move operation is not explicitly declared the destructor is not explicitly declared Defining a move operation disables the automatic generation of copy operations Declaring a move/copy operation as =default counts as an explicit declaration When move operations cannot be synthesized, moving falls into copying Rvalue reference to this struct A { void f(); // bind to any reference of type A ; struct B { void f() &; // bind only to Lvalue void f() &&; // bind only to Rvalue // void f(); // cannot overload one of the above ; int main() { A a; a.f(); A().f(); Part 3 Type deduction B b; b.f(); // calls f() & B().f(); // calls f() && 23 24

7 Contexts for type deduction Type deduction for function templates (1) Type deduction is a compile-time process where the compiler deduces automatically the type of an entity This is done naturally for expressions (the type of which only depends on the constituents of the expression) In C , there is one specific set of rules for type deduction for function templates C adds two new sets of type deduction rules one for self-typing: auto one for operator decltype C extends the usage of auto and decltype Understanding type deduction is crucial for Modern C++ Deducible context A context (an expression) where the compiler needs to deduce the type of some entity template <typename T> void f(t t); int n1 = 10; f(n1); // T deduced from parameter n1 f<int>(3.5); // No deduction for T template <typename T> struct A { void f(t t); ; A<double> a; a.f(x); // No deduction necessary for T since the // compiler knows the type of a, hence T = double Type deduction for function templates (2) Type deduction for function templates (2) There are two types to deduce template <typename T> void f(t& param); f(expr); The type of expr allows to determine T and the type of param Example: const int n1 = 10; f(n1); // expr is of type const int T deduced as const int type of param deduced as const int& Case 1: the parameter is a pointer or a reference, but not a Universal Reference (see further) template <typename T> void f(t param); f(expr); 1. if expr is a reference, ignore the reference part 2. then pattern match the type of expr against the type of param to deduce T int x = 3; const int cx = x; const int& rx = x; template <typename T> void f(t& param); f(x); // T is int, param is int& f(cx); // T is const int, param is const int& f(rx); // T is const int, param is const int& template <typename T> void g(const T& param); g(x); // T is int, param is const int& g(cx); // T is int, param is const int& g(rx); // T is int, param is const int& 27 28

8 Type deduction for function templates (3) Type deduction for function templates (4) Case 2: the parameter is passed by value template <typename T> void f(t param); f(expr); 1. if expr is a reference, ignore the reference part 2. then if expr is const or volatile, ignore this modifier template <typename T> void f(t& param); int x = 3; const int cx = x; const int& rx = x; f(x); // T and param type: int f(cx); // T and param type: int f(rx); // T and param type: int Case 3: the parameter is a Universal Reference (Scott Meyers) that is of the exact form T&& in a deducible context, where T is a template typename parameter This is a special deduction case: see further Type deduction for auto Type deduction for decltype In C++ 11, type deduction for auto is identical to type deduction for template parameter except for initializer list (skipped) auto x = 3; // x is int const auto cx = x; // cx is const int const auto& rx = x; // rx is const int& In C++ 14, auto can be used to automatically deduce function return type auto f(int x) { ; return x * x; // return int for generic lambda parameters transform(li.begin(), li.end(), li.begin(), [] (auto x) { return x * x; ); Operator decltype always return the exact (compile-time) type of an expression including reference, const, volatile int x = 3; const int cx = x; const int& rx = x; decltype(x) x1 = x; // x1 is int decltype(cx) cx1 = cx; // cx1 is const int decltype(rx) rx1 = rx; // rx1 is const int& Use of decltype template <typename T1, typename T2> auto func(t1 t1, T2 t2) -> decltype(t1+t2); template <typename Container, typename Index> auto access(container& c, Index i) -> decltype(c[i]); 31 32

9 Recognizing Universal References Part 4 Universal references A Universal Reference must be of the exact form auto&& or be of the exact form T&&, where T is a template typename parameter no adornment (const, volatile ) is acceptable be used in a deducible context template <typename T> f(t&& t); // T&& is UR template <typename T> f(const T&& t); // NO auto&& x = expr; // OK template <typename T, typename A> void vector<t, A>::emplace(T&& t); // NO, not a deducible context A Universal Reference accepts to be bound to any sort of reference, Rvalues as well as Lvalues memorizes (encodes) which sort of reference is was bound to Special type deduction rule for Universal References Universal References memorize the type of reference passed template <typename T> void f(t&& param); f(expr); 1. if expr is an Lvalue, T and param are deduced to be Lvalue references 2. if expr is a Rvalue, the normal case (Case 1) applies and T is deduced as a non-reference template <typename T> void f(t&& param); int x = 3; const int cx = x; const int& rx = x; f(x); // x is LValue T and param type are int& f(cx); // cx is LValue T and param type are int& f(42); // 42 is RValue T is int and param type is int Universal References and auto auto&& memorizes the type of reference passed int x = 42; const int cx = x; const int& rx = x; auto&& y = 42; // 42 is int and RValue y is int& auto&& cx = x; // cx is const int and LValue // y is const int& auto&& z = x; // x is int and LValue y is int& 35 36

10 Forcing move std::move() std::move() does not move anything! It is an unconditional cast, that transforms any sort of reference into an Rvalue reference Hence the compiler can move the result (if move is available) string s1 = hello ; string s2 = std::move(s1); // s1 moved int s2 // s1 no longer available std::move is safe if restricted to true Rvalue references Do not use it with Universal References Implementation of std::move() (C++14) template <typename T> decltype(auto) move(t&& a) { using rettype = remove_reference_t<t>&&; return static_cast<rettype>(a); Perfect forwarding Perfect forwarding std::forward() (1) std::forward() is a conditional cast which keeps the nature (RValue, LValue, constness) of its parameter if x is an Lvalue, std::forward() returns an Lvalue reference if x is an Rvalue, std::forward() casts to the same Rvalue Implementation of std::forward() template <typename T> T&& forward(remove_reference_t<t>& a) { return static_cast<t&&>(a); Perfect forwarding std::forward() (2) Construction of classes with mixture or RValues/LValues class A { string _s; vector<int> _v A(const string& s, const vector<int>& v) // copy both : _str(s), _vec(v) { A(string&& s, const vector<int>& v) // move first, copy second : _s(std::move(s)), _v(v) { A(const string& s, vector<int>&& v) // copy first, move second : _s(s), _v(std::move(v)) { A(string&& s, vector<int>&& v) // move both : _s(std::move(s)), _v(std::move(v)) { // ; string s =... ; A(s +, vector<int>(10)); // copy both temporaries Need for 4 overloaded constructors? If n parameters, 2 n constructors! Perfect forwarding std::forward() (2) Construction of classes with mixture or RValues/LValues class A { string _s; vector<int> _v A(const string& s, const vector<int>& v) // copy both : _str(s), _vec(v) { A(string&& s, const vector<int>& v) // move first, copy second : _s(std::move(s)), _v(v) { A(const string& s, vector<int>&& v) // copy first, move second : _s(s), _v(std::move(v)) { A(string&& s, vector<int>&& v) // move both : _s(std::move(s)), _v(std::move(v)) { // ; string s =... ; A(s +, vector<int>(10)); // 2 RValues, move both Need for 4 overloaded constructors? If n parameters, 2 n constructors! 39 40

11 Perfect forwarding std::forward() (3) Construction of classes with mixture or RValues/LValues (cont.) class A { string _s; vector<int> _v; template <typename T1, typename T2> A(T1&& s, T2&& v) : _str(std::forward(s)), _vec(std::forward(s)) { ; std::forward() forward its argument, keeping its nature: LValue, RValue, and constness Thus the constructor will choose move for RValues and copy for LValues string s =... ; A(s +, vector<int>(10)); Perfect forwarding std::forward() (4) Despite the use of T&&, the code is type-safe Type compatibility is checked at instantiation (duck typing) T1 must be type-compatible with string and T2 with vector<int> Very flexible: all compatible parameter types can be used One can remove flexibility using static_assert Perfect forwarding is applicable only to function templates Require the special template deduction rule for T&& Universal References are special Rvalue references: reference collapsing rules In C , it is not possible to take a reference to a reference In C , we have the reference collapsing rules A& & A& A& && A& A&& & A& A&& && A&& LValue reference to LValue reference = LValue reference RValue reference to LValue reference = LValue reference LValue reference to RValue reference = LValue reference RValue reference to RValue reference = RValue reference Special template deduction rule for references template <typename T> void f(t&&); if the parameter is a LValue of type A, then T resolves to A&; applying the collapsing rule, the effective parameter type is then A& if the parameter is a RValue of type A, then T resolves to A; the effective parameter type is then A&& More on RValue references (1) RValue references and move semantics are not complicated but they are delicate to handle and there can be several misunderstanding Never return references of any kind to a local automatic object string&& dont_do() { string s = ; return move(s); // NO dangling reference Do not use std::move() on a local automatic object in a return expression string dont_do() { string s = ; return move(s); // NO The compiler will take care of the optimization Do not use move() on expressions that already return a RValue return move(s + ); // NO interferes with compiler optimizations Avoid returning a RValue reference to reference parameters; only move() and forward() should do this 43 44

12 Thomas Becker More on RValue references (2) Introduction to RValue references Scott Meyers Move semantics RValue references and Universal references References-in-Cpp11 Effective Modern C++: 42 specific ways to improve your use of C++11 and C++14, Scott Meyers. O Reilly,

Move Semantics, Rvalue References, and Perfect Forwarding

Move Semantics, Rvalue References, and Perfect Forwarding Move Semantics, Rvalue References, and Perfect Forwarding Scott Meyers, Ph.D. Software Development Consultant smeyers@aristeia.com Voice: 503/638 6028 Fax: 503/974 1887 Last Revised: 3/16/11 C++0x Warning

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 4 Part One: (continued) and 2016 www.cse.unsw.edu.au/ cs6771 2. Inline Constructors, Accessors and Mutators Question (from 2015): In the week 3 examples, constructors

More information

Move semantics. Zoltán Porkoláb: C++11/14 1

Move semantics. Zoltán Porkoláb: C++11/14 1 Move semantics Pointers and arrays References Value vs move semantics Right value references Move semantics in C++11 Perfect forwarding Traps and pitfalls Zoltán Porkoláb: C++11/14 1 Arrays An array is

More information

I m sure you have been annoyed at least once by having to type out types like this:

I m sure you have been annoyed at least once by having to type out types like this: Type Inference The first thing I m going to talk about is type inference. C++11 provides mechanisms which make the compiler deduce the types of expressions. These features allow you to make your code more

More information

Type Inference auto for Note: Note:

Type Inference auto for Note: Note: Type Inference C++11 provides mechanisms for type inference which make the compiler deduce the types of expressions. I m starting the book with type inference because it can make your code more concise

More information

Rvalue References & Move Semantics

Rvalue References & Move Semantics Rvalue References & Move Semantics PB173 Programming in Modern C++ Nikola Beneš, Vladimír Štill, Jiří Weiser Faculty of Informatics, Masaryk University spring 2016 PB173 Modern C++: Rvalue References &

More information

C The new standard

C The new standard C++11 - The new standard Lars Kühne Institut für Informatik Lehrstuhl für theoretische Informatik II Friedrich-Schiller-Universität Jena January 16, 2013 Overview A little bit of history: C++ was initially

More information

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 1 Introduction Definition of Function Overloading Determining which Overload to call How Overload Resolution Works Standard Conversion Sequences

More information

Rvalue References, Move Semantics, Universal References

Rvalue References, Move Semantics, Universal References Rvalue References, Move Semantics, Universal References PV264 Advanced Programming in C++ Nikola Beneš Jan Mrázek Vladimír Štill Faculty of Informatics, Masaryk University Spring 2018 PV264: Rvalue References,

More information

TDDD38 - Advanced programming in C++

TDDD38 - Advanced programming in C++ TDDD38 - Advanced programming in C++ Templates III Christoffer Holm Department of Computer and information science 1 Dependent Names 2 More on Templates 3 SFINAE 1 Dependent Names 2 More on Templates 3

More information

Modernes C++ Träume und Alpträume

Modernes C++ Träume und Alpträume Modernes Träume und Alpträume Nicolai M. Josuttis 5/17 217 by IT-communication.com 1 Independent consultant continuously learning since 1962 Nicolai M. Josuttis Systems Architect, Technical Manager finance,

More information

Advanced Programming & C++ Language

Advanced Programming & C++ Language Advanced Programming & C++ Language ~10~ C++11 new features Ariel University 2018 Dr. Miri (Kopel) Ben-Nissan 2 Evolution of C++ Language What is C++11? 3 C++11 is the ISO C++ standard formally ratified

More information

Overload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019

Overload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019 Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019 1 Introduction Prologue Definition of Function Overloading Determining which Overload to call How Works Standard Conversion Sequences Examples

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

C++ Rvalue References Explained

C++ Rvalue References Explained http://thbecker.net/articles/rvalue_references/section_01.html C++ Rvalue References Explained By Thomas Becker Last updated: March 2013 Contents 1. Introduction 2. Move Semantics 3. Rvalue References

More information

Move semantics. Zoltán Porkoláb: C++11/14 1

Move semantics. Zoltán Porkoláb: C++11/14 1 Move semantics Pointers and arrays References Value vs move semantics Right value references Move semantics in C++11 Perfect forwarding Traps and pitfalls Zoltán Porkoláb: C++11/14 1 Arrays An array is

More information

Copyie Elesion from the C++11 mass. 9 Sep 2016 Pete Williamson

Copyie Elesion from the C++11 mass. 9 Sep 2016 Pete Williamson Copyie Elesion from the C++11 mass 9 Sep 2016 Pete Williamson C++ 11 is a whole new language Links to learning more: http://en.cppreference.com/w/cpp/language/copy_elision https://engdoc.corp.google.com/eng/doc/devguide/cpp/cpp11.shtml?cl=head

More information

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance

More information

Rvalue References as Funny Lvalues

Rvalue References as Funny Lvalues I. Background Document: Author: Date: 2009-11-09 Revision: 1 PL22.16/09-0200 = WG21 N3010 William M. Miller Edison Design Group Rvalue References as Funny Lvalues Rvalue references were introduced into

More information

Lecture 8. Exceptions, Constructor, Templates TDDD86: DALP. Content. Contents Exceptions

Lecture 8. Exceptions, Constructor, Templates TDDD86: DALP. Content. Contents Exceptions Lecture 8 Exceptions, Constructor, Templates TDDD86: DALP Utskriftsversion av Lecture in Data Structures, Algorithms and Programming Paradigms 19th September 2017 Ahmed Rezine, IDA, Linköping University

More information

Value categories. PRvalues. Lvalues

Value categories. PRvalues. Lvalues Value categories v5 Every C++14 expression belongs to exactly one of the following classifications, known as value categories: lvalue, xvalue, prvalue. There's an overlap between these, so a higher level

More information

C++11/14 Rocks. Clang Edition. Alex Korban

C++11/14 Rocks. Clang Edition. Alex Korban C++11/14 Rocks Clang Edition Alex Korban 1 Contents Introduction 9 C++11 guiding principles... 9 Type Inference 11 auto... 11 Some things are still manual... 12 More than syntactic sugar... 12 Why else

More information

Modern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced

Modern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced Department I - C Plus Plus Advanced Modern and Lucid C++ Advanced for Professional Programmers Part 3 Move Semantics Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 09.03.2018 HS2018 Move Semantics 2

More information

New wording for C++0x Lambdas

New wording for C++0x Lambdas 2009-03-19 Daveed Vandevoorde (daveed@edg.com) New wording for C++0x Lambdas Introduction During the meeting of March 2009 in Summit, a large number of issues relating to C++0x Lambdas were raised and

More information

Operator Dot Wording

Operator Dot Wording 2016-10-16 Operator Dot Wording Bjarne Stroustrup (bs@ms.com) Gabriel Dos Reis (gdr@microsoft.com) Abstract This is the proposed wording for allowing a user-defined operator dot (operator.()) for specifying

More information

Other C++11/14 features

Other C++11/14 features Other C++11/14 features Auto, decltype Range for Constexpr Enum class Initializer list Default and delete functions Etc. Zoltán Porkoláb: C++11/14 1 Auto, decltype template void printall(const

More information

Resource Management With a Unique Pointer. Resource Management. Implementing a Unique Pointer Class. Copying and Moving Unique Pointers

Resource Management With a Unique Pointer. Resource Management. Implementing a Unique Pointer Class. Copying and Moving Unique Pointers Resource Management Resource Management With a Unique Pointer Dynamic memory is an example of a resource that is allocated and must be released. void f() { Point* p = new Point(10, 20); // use p delete

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer October 10, 2016 OOPP / C++ Lecture 7... 1/15 Construction and Destruction Kinds of Constructors Move Semantics OOPP / C++ Lecture 7... 2/15

More information

Geheimnisse der Move-Semantik

Geheimnisse der Move-Semantik Geheimnisse der Move-Semantik Nicolai M. Josuttis IT-communication.com 6/16 216 by IT-communication.com 1 Nicolai M. Josuttis Independent consultant continuously learning since 1962 Systems Architect,

More information

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

When we program, we have to deal with errors. Our most basic aim is correctness, but we must Chapter 5 Errors When we program, we have to deal with errors. Our most basic aim is correctness, but we must deal with incomplete problem specifications, incomplete programs, and our own errors. When

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 11 October 3, 2018 CPSC 427, Lecture 11, October 3, 2018 1/24 Copying and Assignment Custody of Objects Move Semantics CPSC 427, Lecture

More information

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43 Advanced C++ 1/43 Overview 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43 1. Expression Value Categories These are not the droids you re looking for ~Obi-wan

More information

Auto - a necessary evil?

Auto - a necessary evil? Auto - a necessary evil? Roger Orr OR/2 Limited ACCU 2013 auto is new in C++11 It has been under discussion for a while, as we shall see Some compilers added support for it early in C++0x so it has had

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

More information

Before we dive in. Preprocessing Compilation Linkage

Before we dive in. Preprocessing Compilation Linkage Templates Before we dive in Preprocessing Compilation Linkage 2 Motivation A useful routine to have is void swap( int& a, int &b ) int tmp = a; a = b; b = tmp; 3 Example What happens if we want to swap

More information

Function Composition and Return Type Deduction. Anthony Williams. 28th February Abstract

Function Composition and Return Type Deduction. Anthony Williams. 28th February Abstract Function Composition and Return Type Deduction Anthony Williams 28th February 2002 Abstract A core feature of functional programming is the ability to build new functions from old ones, such as creating

More information

Outline. 1 About the course

Outline. 1 About the course Outline EDAF50 C++ Programming 1. Introduction 1 About the course Sven Gestegård Robertz Computer Science, LTH 2018 2 Presentation of C++ History Introduction Data types and variables 1. Introduction 2/1

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

CS11 Advanced C++ Spring 2018 Lecture 2

CS11 Advanced C++ Spring 2018 Lecture 2 CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are

More information

C++ Functions. Procedural-based Programming. what s a functions

C++ Functions. Procedural-based Programming. what s a functions C++ Functions Fred Kuhns fredk@cse.wustl.edu Applied Research Laboratory, Department of Computer Science and Engineering, Washington University in St. Louis Washington WASHINGTON UNIVERSITY IN ST LOUIS

More information

04-19 Discussion Notes

04-19 Discussion Notes 04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

C++11 Introduction to the New Standard. Alejandro Cabrera February 1, 2012 Florida State University Department of Computer Science

C++11 Introduction to the New Standard. Alejandro Cabrera February 1, 2012 Florida State University Department of Computer Science C++11 Introduction to the New Standard Alejandro Cabrera February 1, 2012 Florida State University Department of Computer Science Overview A Brief History of C++ Features Improving: Overall Use Meta-programming

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer May 13, 2013 OOPP / C++ Lecture 7... 1/27 Construction and Destruction Allocation and Deallocation Move Semantics Template Classes Example:

More information

Modern C++, From the Beginning to the Middle. Ansel Sermersheim & Barbara Geller ACCU / C++ November 2017

Modern C++, From the Beginning to the Middle. Ansel Sermersheim & Barbara Geller ACCU / C++ November 2017 Modern C++, From the Beginning to the Middle Ansel Sermersheim & Barbara Geller ACCU / C++ November 2017 1 Introduction Where is the Beginning Data Types References Const Const Const Semantics Templates

More information

04-17 Discussion Notes

04-17 Discussion Notes 04-17 Discussion Notes PIC 10B Spring 2018 1 RAII RAII is an acronym for the idiom Resource Acquisition is Initialization. What is meant by resource acquisition is initialization is that a resource should

More information

const-correctness in C++

const-correctness in C++ const-correctness in C++ Matthias Kretz Frankfurt Institute Institute for Computer Science Goethe University Frankfurt 2015-04-01 HGS-HIRe Helmholtz Graduate School for Hadron and Ion Research Matthias

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 21 November 14, 2018 CPSC 427, Lecture 21, November 14, 2018 1/23 Singleton Design Pattern (revisited) More on Functions Casts and Conversions

More information

A Taxonomy of Expression Value Categories

A Taxonomy of Expression Value Categories Document: Author: Date: 2010-03-12 Revision: 6 PL22.16/10-0045 = WG21 N3055 William M. Miller Edison Design Group A Taxonomy of Expression Value Categories Revision History: Revision 6 (PL22.16/10-0045

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

Overview of C Feabhas Ltd 2012

Overview of C Feabhas Ltd 2012 1 2 Copying objects may not be the best solution in many situations. In such cases we typically just want to transfer data from one object to another, rather than make an (expensive, and then discarded)

More information

Structured bindings with polymorphic lambas

Structured bindings with polymorphic lambas 1 Introduction Structured bindings with polymorphic lambas Aaryaman Sagar (aary800@gmail.com) August 14, 2017 This paper proposes usage of structured bindings with polymorphic lambdas, adding them to another

More information

std::optional from Scratch

std::optional from Scratch std::optional from Scratch https://wg21.link/n4606 http://en.cppreference.com/w/cpp/utility/optional http://codereview.stackexchange.com/questions/127498/an-optionalt-implementation An optional object

More information

Types and Type Inference

Types and Type Inference Types and Type Inference Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on the course homepage Outline General discussion

More information

C++11 Move Constructors and Move Assignment. For Introduction to C++ Programming By Y. Daniel Liang

C++11 Move Constructors and Move Assignment. For Introduction to C++ Programming By Y. Daniel Liang C++11 Move Constructors and Move Assignment For Introduction to C++ Programming By Y. Daniel Liang C+11 provides move constructors and move assignment to improve performance by moving a large rvalue object

More information

Operator Dot Wording

Operator Dot Wording WG21-P0252R0 2016-02-13 Operator Dot Wording Bjarne Stroustrup (bs@ms.com) Gabriel Dos Reis (gdr@microsoft.com) Abstract This is the proposed wording for allowing a user-defined operator dot (operator.())

More information

Remedial C Now that we can actually use it Pete Williamson

Remedial C Now that we can actually use it Pete Williamson Remedial C++ 11 Now that we can actually use it Pete Williamson (petewil00@hotmail.com) Overview (1) auto lambdas nullptr = default, = delete shared_ptr Range based for loops Overview (2) Uniform initialization

More information

Polymorphism. Zimmer CSCI 330

Polymorphism. Zimmer CSCI 330 Polymorphism Polymorphism - is the property of OOP that allows the run-time binding of a function's name to the code that implements the function. (Run-time binding to the starting address of the code.)

More information

Special Member Functions

Special Member Functions CS 247: Software Engineering Principles Special Member Functions Readings: Eckel, Vol. 1 Ch. 11 References and the Copy Constructor Ch. 12 Operator Overloading ( operator= ) U Waterloo CS247 (Spring 2017)

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Deducing the type of variable from its initializer expression (revision 3)

Deducing the type of variable from its initializer expression (revision 3) Deducing the type of variable from its initializer expression (revision 3) Programming Language C++ Document no: N1894=05-0154 Jaakko Järvi Texas A&M University College Station, TX jarvi@cs.tamu.edu Bjarne

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages CSE 307: Principles of Programming Languages Variables and Constants R. Sekar 1 / 22 Topics 2 / 22 Variables and Constants Variables are stored in memory, whereas constants need not be. Value of variables

More information

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

ENERGY 211 / CME 211. Functions

ENERGY 211 / CME 211. Functions ENERGY 211 / CME 211 Lecture 8 October 8, 2008 1 Functions So far, we have seen programs in which all code resides within a main function Complex programs consist of subprograms that perform particular

More information

Advanced C++ Topics. Alexander Warg, 2017

Advanced C++ Topics. Alexander Warg, 2017 www.kernkonzept.com Advanced C++ Topics Alexander Warg, 2017 M I C R O K E R N E L M A D E I N G E R M A N Y Overview WHAT IS BEHIND C++ Language Magics Object Life Time Object Memory Layout INTRODUCTION

More information

Qualified std::function signatures

Qualified std::function signatures Document number: P0045R1 Date: 2017 02 06 To: SC22/WG21 LEWG Reply to: David Krauss (david_work at me dot com) Qualified std::function signatures std::function implements type-erasure of the behavior of

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively

More information

Outline. Function calls and results Returning objects by value. return value optimization (RVO) Call by reference or by value?

Outline. Function calls and results Returning objects by value. return value optimization (RVO) Call by reference or by value? Outline EDAF50 C++ Programming 6... 1 Function calls 2 Sven Gestegård Robertz Computer Science, LTH 2018 3 Standard library algorithms Insert iterators 4 Iterators Different kinds of iterators stream iterators

More information

Polymorphism and Type Inference

Polymorphism and Type Inference Polymorphism and Type Inference Volker Stolz stolz@ifi.uio.no INF 3110-2008 Department of Informatics University of Oslo Initially by Gerardo Schneider. Based on John C. Mitchell s slides (Stanford U.)

More information

Database Systems on Modern CPU Architectures

Database Systems on Modern CPU Architectures Database Systems on Modern CPU Architectures Introduction to Modern C++ Moritz Sichert Technische Universität München Department of Informatics Chair of Data Science and Engineering Overview Prerequisites:

More information

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova Object-Oriented Programming, Iouliia Skliarova A reference (&) is like a constant pointer that is automatically dereferenced. There are certain rules when using references: 1. A reference must be initialized

More information

Generic Programming. Akim D le Étienne Renault Roland Levillain

Generic Programming. Akim D le Étienne Renault Roland Levillain Generic Programming Akim Demaille Étienne Renault Roland Levillain first.last@lrde.epita.fr EPITA École Pour l Informatique et les Techniques Avancées June 8, 2017 Generic Programming 1 Some definitions

More information

Expansion statements. Version history. Introduction. Basic usage

Expansion statements. Version history. Introduction. Basic usage Expansion statements Version history Document: P1306R0 Revises: P0589R0 Date: 08 10 2018 Audience: EWG Authors: Andrew Sutton (asutton@uakron.edu) Sam Goodrick (sgoodrick@lock3software.com) Daveed Vandevoorde

More information

Deducing the type of variable from its initializer expression (revision 4)

Deducing the type of variable from its initializer expression (revision 4) Deducing the type of variable from its initializer expression (revision 4) Programming Language C++ Document no: N1984=06-0054 Jaakko Järvi Texas A&M University College Station, TX jarvi@cs.tamu.edu Bjarne

More information

Introduction to C++11 and its use inside Qt

Introduction to C++11 and its use inside Qt Introduction to C++11 and its use inside Qt Olivier Goffart February 2013 1/43 Introduction to C++11 and its use inside Qt About Me http://woboq.com http://code.woboq.org 2/43 Introduction to C++11 and

More information

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?

More information

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

12. Dictionaries. Dictionary. Idea. Other idea

12. Dictionaries. Dictionary. Idea. Other idea Dictionary 12. Dictionaries Dictionary, Self-ordering List, Implementation of Dictionaries with Array / List /Sip lists. [Ottman/Widmayer, Kap. 3.3,1.7, Cormen et al, Kap. Problem 17-5] ADT to manage eys

More information

EXP54-CPP. Do not access an object outside of its lifetime

EXP54-CPP. Do not access an object outside of its lifetime EXP54-CPP. Do not access an object outside of its lifetime Every object has a lifetime in which it can be used in a well-defined manner. The lifetime of an object begins when sufficient, properly aligned

More information

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides.

cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. cs242 Kathleen Fisher Reading: Concepts in Programming Languages, Chapter 6 Thanks to John Mitchell for some of these slides. We are looking for homework graders. If you are interested, send mail to cs242cs.stanford.edu

More information

Types, Type Inference and Unification

Types, Type Inference and Unification Types, Type Inference and Unification Mooly Sagiv Slides by Kathleen Fisher and John Mitchell Cornell CS 6110 Summary (Functional Programming) Lambda Calculus Basic ML Advanced ML: Modules, References,

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

Working with Batches of Data

Working with Batches of Data Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Abstract So far we looked at simple read a string print a string problems. Now we will look at more complex problems

More information

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things. A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators

More information

A <Basic> C++ Course

A <Basic> C++ Course adapted from Jean-Paul Rigault courses 1 A C++ Course 8 Object-oriented programming 2 Julien Deantoni 2 Outline Dynamic Typing Truncature Cast 3 Variants of class Paragraph Definition of derived

More information

GridKa School 2013: Effective Analysis C++ Templates

GridKa School 2013: Effective Analysis C++ Templates GridKa School 2013: Effective Analysis C++ Templates Introduction Jörg Meyer, Steinbuch Centre for Computing, Scientific Data Management KIT University of the State of Baden-Wuerttemberg and National Research

More information

Copy Constructors & Destructors

Copy Constructors & Destructors Copy Constructors & Destructors 2-07-2013 Implementing a vector class local functions implicit constructors Destructors Copy Constructors Project #1: MiniMusicPlayer Quiz today 2/7/13 vectors and reading

More information

Deducing the type of variable from its initializer expression Programming Language C++ Document no: N1721=

Deducing the type of variable from its initializer expression Programming Language C++ Document no: N1721= Deducing the type of variable from its initializer expression Programming Language C++ Document no: N1721=04-0161 Jaakko Järvi Texas A&M University College Station, TX jarvi@cs.tamu.edu Bjarne Stroustrup

More information

Lambdas in unevaluated contexts

Lambdas in unevaluated contexts Lambdas in unevaluated contexts Document #: P0315R2 Date: 2017-06-18 Project: Programming Language C++ Audience: Core Working Group Reply-to: Louis Dionne Hubert Tong

More information

Make Classes Useful Again

Make Classes Useful Again Make Classes Useful Again CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 11 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona

More information

BYOD - WEEK 3 AGENDA. Dictionary Encoding. Organization. Sprint 3

BYOD - WEEK 3 AGENDA. Dictionary Encoding. Organization. Sprint 3 WEEK 3 BYOD BYOD - WEEK 3 AGENDA Dictionary Encoding Organization Sprint 3 2 BYOD - WEEK 3 DICTIONARY ENCODING - MOTIVATION 3 Memory access is the new bottleneck Decrease number of bits used for data representation

More information

Type Systems, Type Inference, and Polymorphism

Type Systems, Type Inference, and Polymorphism 6 Type Systems, Type Inference, and Polymorphism Programming involves a wide range of computational constructs, such as data structures, functions, objects, communication channels, and threads of control.

More information

Working Draft, C++ extensions for Concepts

Working Draft, C++ extensions for Concepts Document Number: Date: 2017-06-19 Revises: N4641 Reply to: Andrew Sutton University of Akron asutton@uakron.edu Working Draft, C++ extensions for Concepts Note: this is an early draft. It s known to be

More information