Advanced C ++ Philip Blakely. Laboratory for Scientific Computing, University of Cambridge. Philip Blakely (LSC) Advanced C++ 1 / 119
|
|
- Victor Carter
- 5 years ago
- Views:
Transcription
1 Advanced C ++ Philip Blakely Laboratory for Scientific Computing, University of Cambridge Philip Blakely (LSC) Advanced C++ 1 / 119
2 Part I C Philip Blakely (LSC) Advanced C++ 2 / 119
3 C C was standardized in You may see references to C ++ 0x in old documentation. It incorporates useful constructs from the Boost libraries. New container types. Lambda functions Features geared towards ease of optimization. These lectures assume that you are a reasonably competent C ++ user. Check what version of C ++ your compiler defaults to. For gcc use the --std=c++11 flag. Philip Blakely (LSC) Advanced C++ 3 / 119
4 References Bjarne s guide to differences between C and C ++ 11: Bjarne Stroustrup, The C ++ Programming Language, 4th Edition, Addison Wesley - has clear indication of which features are in C and C (and C and C ++ 17). Virtually every topic in this course has an associated example code in the Examples directory. In some cases I have used the macro AVOID INTENTIONAL ERRORS to allow me to check for correct compilation. Philip Blakely (LSC) Advanced C++ 4 / 119
5 Detecting C If you write code that requires C syntax, and someone accidentally compiles with a C compiler, then they will have a large number of errors. A simple way to detect whether you have a C compiler is: #if cplusplus < L #error This program requires a C++11 compiler. #endif The equivalent numbers for all versions are: L (C ++ 98) L (C ++ 11) L (C ++ 14) L (C ++ 17) Philip Blakely (LSC) Advanced C++ 5 / 119
6 NULL pointer In C you would use NULL or 0 to represent an undefined pointer. In C you should use nullptr instead. This provides for better readability and for distinctness in overloading to accept either an integer or a pointer. See Examples/null.C Philip Blakely (LSC) Advanced C++ 6 / 119
7 enum classes In C we had enums: enum Colour{Red, Green, Blue; which defines a type Colour at global scope that implicitly converts to an int: Colour b = Blue; int r = Red; In C we have a strongly typed enum class: enum class ProperColour : char { Cyan, Magenta, Yellow, Black ; which defines a type ProperColour with its own scope that uses a char to store its value, but does not implicitly convert to an char: ProperColour c = ProperColour::Cyan; char y = (char)propercolour::yellow; See Examples/enum.C Philip Blakely (LSC) Advanced C++ 7 / 119
8 Template closing brackets A problem you didn t know you had: std::vector<std::pair<int,int>> a; is invalid in C In C >> is interpreted as a right-shift operator, following the maximal munch principle. In C you need a space between the two > brackets. From C the above syntax is valid. In some (fairly contrived) cases, this may cause code to give different results under C and C See /n1757.html See Examples/maxMunch.C. Philip Blakely (LSC) Advanced C++ 8 / 119
9 Constant values Template parameters (for example) must have their values known at compile-time. In C we are restricted to using static const int members and using recursive templates if we want to do any complex calculations. In C we can declare a function to be a constexpr, specifying that it can be evaluated at compile-time: constexpr int triang(int n){ return (n>1)? n + triang(n 1) : 1; We can then use it as a template parameter (Examples/constexpr.C): template<int D> struct Vector{ double m data[d]; ; Vector<triang(5)> a; Philip Blakely (LSC) Advanced C++ 9 / 119
10 Constant values There are restrictions to using constexpr: It must consist of a single return statement. It must not contain any local variables. It must not have side-effects, e.g. modifying a global variable. A constexpr function can be used to initialize any static const member. Philip Blakely (LSC) Advanced C++ 10 / 119
11 Constant values - non-integral Note that non-integral static const members are now permitted in C ++ 11, and can be initialized inside the class: constexpr double expon(double n){ return exp(n); template<int D> struct Vector{ static constexpr double m val = expon(d); ; See Examples/constexprfloat.C Philip Blakely (LSC) Advanced C++ 11 / 119
12 Automatic type declarations Consider the following C code: int countpassengers(const std::list<const Vehicle >& vehicles){ int numpass = 0; for(std::list<const Vehicle >::const iterator it = vehicles.begin() ; it!= vehicles.end() ; ++it ){ numpass += it >numpass(); return numpass; The type of it is complicated to type, and adds length to the code line without adding useful information. In C we can type: for(auto it = vehicles.begin() ; it!= vehicles.end() ; ++it ){ The auto keyword declares the variable it to be the exact type on the right of the equality. Philip Blakely (LSC) Advanced C++ 12 / 119
13 Initializer lists In C initializing a std::vector of values was annoying: std::vector<int> a(4); a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 5; (Even initializing from int a2[4] = {1,2,3,5 is awkward.) There is an easier way in C ++ 11: std::vector<int> a{1, 2, 3, 5; This works for std::list as well. Similarly, for a std::map: std::map<int, double> b{ {1, M PI, {2, M E, {6, See Examples/init-list.C Philip Blakely (LSC) Advanced C++ 13 / 119
14 Initializer list constructors How can you use this syntax in your own constructors? We would like to have: Matrix rotate{{cos(theta), sin(theta), {+sin(theta), cos(theta); C provides a special type which is passed to constructors: std::initializer list, requiring the header #include <initializer list> This acts as a generic container, which can be iterated over, with the bare minimum of begin(), end(), size() Philip Blakely (LSC) Advanced C++ 14 / 119
15 Initializer list constructors For a 2 2 matrix class: Matrix::Matrix(std::initializer list< std::pair<double, double>> args){ size t i=0; for(auto it = args.begin() ; it!= args.end() ; ++it, ++i){ data[i][0] = ( it).first; data[i][1] = ( it).second; For each pair of doubles in the provided list, we set the elements of data[2][2]. Matrix m{{0, 1, {3, 4; This could be extended to generic-sized matrices via an initializer list<std::vector<double> > See Examples/init-list.C Philip Blakely (LSC) Advanced C++ 15 / 119
16 Automatic type declarations ctd The std::max function takes the form: template<typename T> max(const T& t1, const T& t2){... which causes an error if you try to call std::max(1, 2.0). The solution is to use std::max<double>(1, 2.0). Consider the following alternative: template<typename T1, typename T2> TYPE max(const T1& t1, const T2& t2){ return (t1 > t2)? t1 : t2; What goes in place of the TYPE? It can t be T1 or T2 themselves. We can use typename std::common type<t1, T2>::type This is defined to be the resulting type of (true)? t1 : t2. (Strictly it s (true)? declval<t1>() : declval<t2>()) See Examples/max.C Philip Blakely (LSC) Advanced C++ 16 / 119
17 Automatic type declarations ctd A similar problem to the above is: template<typename T, typename S>?? operator (const std::vector<t>& v, const S& s) i.e. multiplication of a vector class with elements of type T by a scalar of type S. What if T = int and S = double? You could start using std::common type but this may not work if you start creating your own types. The solution is decltype: template<typename T, typename S> auto operator (const std::vector<t>& v, const S& s) > std::vector<decltype(t{ S{)> {... This syntax declares the result s contained type to be the type that would result from the product of scalars of types T and S. See Examples/vector.C Philip Blakely (LSC) Advanced C++ 17 / 119
18 Range-based for loops In C we often had the following long syntax: for(std::list<int>::const iterator iter = l.begin() ; iter!= l.end() ; ++iter) In C we can use: for( const int& i : l ){ std::cout << i << ", "; for( int& i : l ){ i = 2; We can even iterate over an in-place array: for(double p : {1., 4., 9., 10., M PI ){ std::cout << "sqrt(" << p << ") = " << sqrt(p); See Examples/for-loops.C. Philip Blakely (LSC) Advanced C++ 18 / 119
19 noexcept In C it was possible to indicate that certain functions would never throw an exception, using throw(). In C this is replaced by noexcept: Vector::Vector()noexcept{ m data = nullptr; m size = 0; noexcept is part of the function signature in the same way as const, for example. If a noexcept function does throw an exception, the program will immediately terminate. This differs from default behaviour which would require that the exception propagate up the function stack until a matching catch() was found. Philip Blakely (LSC) Advanced C++ 19 / 119
20 Return Value Optimization Consider the overloaded operator: Vector operator+(const Vector& a, const Vector& b){ Vector c(a.size()); for(size t i=0 ; i < a.size() ; i++){ c[i] = a[i] + b[i]; return c; Vector d = a + b; In C ++ 03, with typical copy/assign-constructors, this can result in c being created, then copied into a newly created d. This seems wasteful, as c will immediately be destroyed. The Return Value Optimization allows compilers to avoid making this copy, and only creating the final destination d. In fact, gcc will do this at -O0 unless you explicitly disable it via -fno-elide-constructors. See Examples/move.C, compiling in C mode with and without -fno-elide-constructors. Philip Blakely (LSC) Advanced C++ 20 / 119
21 Thwarting the Return Value Optimization However the RVO is easily thwarted by adding the following (not entirely unreasonable) code into operator+: if(a.size()!= b.size()){ return Vector(0); There is no longer a single return point from the function, and the result Vector is not necessarily always the same one. Now, if we compile move.c with -DFORCE COPY in C mode, it includes the above code and we always have a copy-constructor call. Thus, adding the above will result in (possibly) slower code than before, for no particularly good reason. Philip Blakely (LSC) Advanced C++ 21 / 119
22 Move syntax C provides a way to move an object instead of copying it. This is used when we know the object being copied from will no longer be used (e.g. the returned c in the previous example). Vector(Vector&& a){ m size = a.m size; m data = a.m data; a.m data = NULL; a.m size = 0; Instead of copying the data element by element, we copy the data pointer itself. We cannot write the normal copy-constructor this way because then two Vectors would point to the same data. Note that since a is about to be destroyed, its contents must be something that the destructor will handle safely. Compiling Examples/move.C with C support results in no slow copy functions being called. Philip Blakely (LSC) Advanced C++ 22 / 119
23 Move into containers There are now functions to add elements to containers using move-syntax: std::vector<vector> vecs; Vector a(10); vecs.push back(std::move(a)); The std::move syntax comes from the <utility> header, and indicates that the variable should be moved rather than copied. Since we defined the Vector::Vector(Vector&& v) function to invalidate the contents of v, the size of a above will be zero after the std::move() call. You should not attempt to use a after the above has been called. See Examples/moveContainer.C. Philip Blakely (LSC) Advanced C++ 23 / 119
24 Move into containers Following the principles of Resource Allocation Is Initialization (RAII), std containers will attempt to move their elements, but only if the move operation is guaranteed not to throw an exception. If a std::vector needs to copy all of its data into a new region of memory (due to a push back for example), it will use the normal copy constructor unless it is guaranteed that the move-constructor will not throw an exception. So, we should declare the move-constuctor noexcept: Vector(Vector&& a)noexcept {... Then, multiple insertions into an std::vector will not result in any slow copies. Philip Blakely (LSC) Advanced C++ 24 / 119
25 Move into containers Examples/moveContainer.C demonstrates a copy-insertion, an in-place construct and push-back, and an explicit moving push-back: vecs.push back(a); vecs.push back(vector(10)); vecs.push back(std::move(a)); With fully implemented move functions, only the first one performs a slow copy. If we omit the noexcept, then slow copies result when the vector has to reallocate its memory. Philip Blakely (LSC) Advanced C++ 25 / 119
26 Emplace If move semantics had not been implemented for Vector, then: vecs.push back(vector(10)); causes a construction and then copy-construct. Even with move semantics, it still causes a construct and move. However, an emplace will construct in-place: vecs.emplace back(10); The 10 corresponds to the parameters to be passed to the constructor. Other emplace functions are available for various containers, e.g: std::list<int> numbers; numbers.emplace(iter, 20) where the iterator indicates the position before which to insert the new element. std::map<std::string, int> ages; ages.emplace("tom", 10); Philip Blakely (LSC) Advanced C++ 26 / 119
27 Move/Emplace performance As usual, you should consider readability before performance. The only reason that move-semantics give better performance is that there are non-trivial resources associated with a Vector. The emplace approach only avoids an extra move call. However, if we did not have move-semantics, and used emplace, it would save a copy-construct. Philip Blakely (LSC) Advanced C++ 27 / 119
28 New containers: forward list As an alternative to std::list, which is bidirectional, forward list is singly-linked. It is more space-efficient than std::list. Philip Blakely (LSC) Advanced C++ 28 / 119
29 New containers: unordered map Recall that a std::map<key, Value> relies on an ordering on the Key type. This allows a new element to be inserted with complexity O(log(N)) where N is the number of elements in the map. It is likely that the map is implemented as a binary-tree so that searching for the correct insertion point requires searching down tree branches. (There is the option to insert using an iterator as a hint where to put the new element.) What if you have a Key with no ordering? C now has a hashed map, called std::unordered map. Philip Blakely (LSC) Advanced C++ 29 / 119
30 New containers: unordered map std::unordered map<key, Value> relies on the existence of a hash function from Key to size t. The cost of insertion is now O(1). The third template parameter is a functional which defaults to std::hash<key> and is defined for all basic types, strings and a few other types (not containers). The hash functional maps a Key type to a size t and should map different Keys to different values as far as possible. If a hash-collision occurs, then a bucket is created to hold all Keys that hash to this value. A poor hash function can therefore reduce the efficiency of a std::unordered map to have O(N) complexity for insertion if many hash-collisions occur. Philip Blakely (LSC) Advanced C++ 30 / 119
31 Creating a new hash functional Suppose we have a 2D coordinate type: struct Coord{ Coord(int i, int j) : x(i), y(j){ bool operator==(const Coord& b)const{ return (x == b.x) && (y == b.y); int x; int y; ; Create a functional: struct hashcoord{ size t operator()(const Coord& a)const{ return std::hash<int>()(a.x) ˆ std::hash<int>()(a.y); ; Note that std::hash<int> is a type, so std::hash<int>() is an object of that type, which has an operator operator()(int) Philip Blakely (LSC) Advanced C++ 31 / 119
32 Creating a new hash functional The ^ exclusive OR operator ensures that the results of the underlying hash functions are combined so as to give a result which is also size t. Now we can use the Coord as a key as follows: std::unordered map<coord, double, hashcoord> cellvalues; Coord a(1,3); cellvalues[a] = 3.0; See Examples/unordered map.c Philip Blakely (LSC) Advanced C++ 32 / 119
33 New containers: unordered map There are other related new containers: std::unordered set std::unordered multiset std::unordered multimap Philip Blakely (LSC) Advanced C++ 33 / 119
34 New containers: array C now has a fixed-size array type, essentially containing a C-like array: #include <array> std::array<double, 5> a{1,4,9,16,25; a[2] = 36; std::sort(a.begin(), a.end()); for(size t i=0 ; i < a.size() ; i++){ std::cout << "a[" << i << "] = " << a[i] << std::endl; Importantly, this does not decay to a double* when being passed to a function. See Examples/array.C Philip Blakely (LSC) Advanced C++ 34 / 119
Part X. Advanced C ++
Part X Advanced C ++ topics Philip Blakely (LSC) Advanced C++ 158 / 217 References The following are highly regarded books. They are fairly in-depth, and I haven t read them in their entirity. However,
More informationPart XI. Algorithms and Templates. Philip Blakely (LSC) C++ Introduction 314 / 370
Part XI Algorithms and Templates Philip Blakely (LSC) C++ Introduction 314 / 370 STL Algorithms Outline 44 STL Algorithms 45 Templates 46 Summing an array 47 Templated classes Philip Blakely (LSC) C++
More informationPart III. Advanced C ++
Part III Advanced C ++ topics Philip Blakely (LSC) Advanced C++ 66 / 119 References The following are highly regarded books. They are fairly in-depth, and I haven t read them in their entirity. However,
More informationPart II. C continued. Philip Blakely (LSC) Advanced C++ 35 / 119
Part II C ++ 11 continued Philip Blakely (LSC) Advanced C++ 35 / 119 Delegated constructor In C ++ 03, if there is common code between constructors, you have to create an init() or similar function: class
More informationCS
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 informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Traits and Policies Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer Semester
More informationOutline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O
Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references
More informationC++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.
C++11: 10 Features You Should be Using Gordon Brown @AerialMantis R&D Runtime Engineer Codeplay Software Ltd. Agenda Default and Deleted Methods Static Assertions Delegated and Inherited Constructors Null
More informationOperator overloading
1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The
More informationstd::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 informationA Crash Course in (Some of) Modern C++
CMPT 373 Software Development Methods A Crash Course in (Some of) Modern C++ Nick Sumner wsumner@sfu.ca With material from Bjarne Stroustrup & Herb Sutter C++ was complicated/intimidating Pointers Arithmetic
More informationC 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 informationC++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 information04-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 informationG52CPP C++ Programming Lecture 20
G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not
More informationuse static size for this buffer
Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation
More informationRvalue 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 informationShort 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 informationAIMS Embedded Systems Programming MT 2017
AIMS Embedded Systems Programming MT 2017 Object-Oriented Programming with C++ Daniel Kroening University of Oxford, Computer Science Department Version 1.0, 2014 Outline Classes and Objects Constructors
More informationWeek 8: Operator overloading
Due to various disruptions, we did not get through all the material in the slides below. CS319: Scientific Computing (with C++) Week 8: Operator overloading 1 The copy constructor 2 Operator Overloading
More informationIBM Rational Rhapsody TestConductor Add On. Code Coverage Limitations
IBM Rational Rhapsody TestConductor Add On Code Coverage Limitations 1 Rhapsody IBM Rational Rhapsody TestConductor Add On Code Coverage Limitations Release 2.7.1 2 License Agreement No part of this publication
More informationCS201 - 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 informationPart VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370
Part VII Object-Oriented Programming Philip Blakely (LSC) C++ Introduction 194 / 370 OOP Outline 24 Object-Oriented Programming 25 Member functions 26 Constructors 27 Destructors 28 More constructors Philip
More informationMidterm Review. PIC 10B Spring 2018
Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed
More informationI 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 informationPart V. Memory and pointers. Philip Blakely (LSC) C++ Introduction 145 / 370
Part V and pointers Philip Blakely (LSC) C++ Introduction 145 / 370 Outline 19 20 Function pointers 21 Global variables Philip Blakely (LSC) C++ Introduction 146 / 370 Heap and Stack The stack is a Last-In-First-Out
More informationA 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 informationType 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 informationSplicing Maps and Sets (Revision 1)
Document number: N3645 Date: 2013-05-04 Project: Programming Language C++ Reference: N3485 Reply to: Alan Talbot cpp@alantalbot.com Howard Hinnant howard.hinnant@gmail.com James Dennett jdennett@google.com
More informationObject-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... IntArray B (100); // IntArray with 100 elements, each initialized to 0
Types with External Resources A class constructor is invoked when an object comes into scope. The constructor prepares the object by creating an environment in which the member functions operate. For many
More informationObject-Oriented Programming
- oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne
More informationInterview Questions of C++
Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.
More informationPIC 10A Objects/Classes
PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous
More informationAn Introduction to Template Metaprogramming
An Introduction to Template Metaprogramming Barney Dellar Software Team Lead Toshiba Medical Visualisation Systems Caveat I decided to do this talk after getting thoroughly lost on the recent talk on SFINAE.
More informationPart XII. More programming comments. Philip Blakely (LSC) C++ Introduction 349 / 370
Part XII More programming comments Philip Blakely (LSC) C++ Introduction 349 / 370 Namespaces Outline 48 Namespaces 49 Exceptions 50 Programming practice and style Philip Blakely (LSC) C++ Introduction
More informationThe C++ Programming Language, Core Working Group. Title: Unary Folds and Empty Parameter Packs (revision 1)
1 Document number: P0036 Date: 2015-09-10 Project: The C++ Programming Language, Core Working Group Title: Unary Folds and Empty Parameter Packs (revision 1) Revises: N4358 Reply-to: Thibaut Le Jehan lejehan.thibaut@gmail.com
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationRemedial 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 informationAn Introduction to C++
An Introduction to C++ Introduction to C++ C++ classes C++ class details To create a complex type in C In the.h file Define structs to store data Declare function prototypes The.h file serves as the interface
More informationSTL Quick Reference for CS 241
STL Quick Reference for CS 241 Spring 2018 The purpose of this document is to provide basic information on those elements of the C++14 standard library we think are most likely to be needed in CS 241.
More informationOther 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 informationEL2310 Scientific Programming
Lecture 16: STL, C++1y (ramviyas@kth.se) Overview Overview Lecture 16: STL and C++1y Reminders Wrap up C++11 Reminders The help sessions and deadline C++ help session: Fri 24.10.2015, 15:00-17:00, Room
More informationQUIZ. What is wrong with this code that uses default arguments?
QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code
More informationC++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 informationA Proposal to Add a Const-Propagating Wrapper to the Standard Library
Doc number: N4057 Revises: N3973 Date: 2014-07-02 Project: Programming Language C++, Library Evolution Working Group Reply-to: Jonathan Coe Robert Mill A Proposal
More informationExpansion 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 informationOverview. 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 informationWhen 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 informationIntroduction to C ++
Introduction to C ++ Philip Blakely Laboratory for Scientific Computing, University of Cambridge Philip Blakely (LSC) C++ Introduction 1 / 370 Part I Getting Started Philip Blakely (LSC) C++ Introduction
More informationImprove your C++! John Richardson. Lab Study Meeting 2013
Improve your C++! John Richardson Lab Study Meeting 2013 Objectives How do I use the standard library correctly? What is C++11? Should I use it? Skills for debugging...? What kind of profiling is possible
More informationCPSC 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 informationLesson 13 - Vectors Dynamic Data Storage
Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts
More informationCOSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26
COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.
More informationProgramming in C and C++
Programming in C and C++ 5. C++: Overloading, Namespaces, and Classes Dr. Neel Krishnaswami University of Cambridge (based on notes from and with thanks to Anil Madhavapeddy, Alan Mycroft, Alastair Beresford
More informationOperator 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 informationCS93SI Handout 04 Spring 2006 Apr Review Answers
CS93SI Handout 04 Spring 2006 Apr 6 2006 Review Answers I promised answers to these questions, so here they are. I'll probably readdress the most important of these over and over again, so it's not terribly
More informationC++11 and Compiler Update
C++11 and Compiler Update John JT Thomas Sr. Director Application Developer Products About this Session A Brief History Features of C++11 you should be using now Questions 2 Bjarne Stroustrup C with Objects
More informationMARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012
MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)
More informationAppendix. 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 informationObjects Managing a Resource
Objects Managing a Resource 1 What is a Resource Respects Release/Acquire protocol files (open/close) memory allocation (allocate/free) locks (acquire/release). 2 What is a Resource Objects when constructed,
More informationDebug C++ Without Running. Anastasia Kazakova
Debug C++ Without Running Anastasia Kazakova JetBrains @anastasiak2512 Agenda 1. Tricky C++ language. Show samples! 2. Seems to help but it doesn t. Why? Running / Debugging Static / dynamic code analysis
More information05-01 Discussion Notes
05-01 Discussion Notes PIC 10B Spring 2018 1 Exceptions 1.1 Introduction Exceptions are used to signify that a function is being used incorrectly. Once an exception is thrown, it is up to the programmer
More informationProject Compiler. CS031 TA Help Session November 28, 2011
Project Compiler CS031 TA Help Session November 28, 2011 Motivation Generally, it s easier to program in higher-level languages than in assembly. Our goal is to automate the conversion from a higher-level
More informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More information1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?
1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity
More informationCOMP6771 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 informationSymbol Tables. ASU Textbook Chapter 7.6, 6.5 and 6.3. Tsan-sheng Hsu.
Symbol Tables ASU Textbook Chapter 7.6, 6.5 and 6.3 Tsan-sheng Hsu tshsu@iis.sinica.edu.tw http://www.iis.sinica.edu.tw/~tshsu 1 Definitions Symbol table: A data structure used by a compiler to keep track
More information2 ADT Programming User-defined abstract data types
Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct
More informationImplicit Evaluation of auto Variables and Arguments
Implicit Evaluation of auto Variables and Arguments Document number: N3748 Authors: Joël Falcou University Paris XI, LRI Peter Gottschling SimuNova Herb Sutter Microsoft Date: 2013-08-30 Project: Programming
More informationSoftware Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example
Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell
More informationA polymorphic value-type for C++
A polymorphic value-type for C++ ISO/IEC JTC1 SC22 WG21 Programming Language C++ P0201R2 Working Group: Library Evolution Date: 2017-10-16 Jonathan Coe Sean Parent
More informationEXP54-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 informationSTRICT_VARIANT. A simpler variant in C++ Chris Beck
STRICT_VARIANT A simpler variant in C++ Chris Beck https://github.com/cbeck88/strict_variant What is a variant? A variant is a heterogenous container. std::vector many objects of one type std::variant
More informationBasic Types, Variables, Literals, Constants
Basic Types, Variables, Literals, Constants What is in a Word? A byte is the basic addressable unit of memory in RAM Typically it is 8 bits (octet) But some machines had 7, or 9, or... A word is the basic
More informationCS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms
CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()
More informationOutline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor
Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened
More informationCSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington
CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning
More informationC++ Objects Overloading Other C++ Peter Kristensen
Peter Kristensen 2012-12-03 Peter Kristensen Outline 1 What s this thing anyway 2 3 Functions Operators 4 Templates STL A better C 11 Peter Kristensen Overview What s this thing anyway 1 What s this thing
More informationWhat will happen if we try to compile, link and run this program? Do you have any comments to the code?
1 # include < iostream > 2 3 int main () 4 { 5 std :: cout
More informationTDDD38 - 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 informationCMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC
CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible
More information1 of 8 3/28/2010 8:03 AM C++ Special Topics Home Class Info Links Lectures Newsgroup Assignmen This is a short review of special topics in C++ especially helpful for various assignments. These notes are
More informationCSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)
CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too) HW6 NOTE: Do not use the STL map or STL pair for HW6. (It s okay to use them for the contest.)
More informationLecture Topics. Administrivia
ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality
More informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More information5 Assignment 3 [Assignment ID:cpp_arithmetic]
SENG 475 & ECE 596C, Summer 2019 5-1 5 Assignment 3 [Assignment ID:cpp_arithmetic] 5.1 Preamble (Please Read Carefully) Before starting work on this assignment, it is critically important that you carefully
More informationInstantiation 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 informationKOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming
KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OPERATOR OVERLOADING KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 Dynamic Memory Management
More information1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!
//Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new
More informationRvalue 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 informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 08 Constants and Inline Functions Welcome to module 6 of Programming
More informationScientific programming (in C++)
Scientific programming (in C++) F. Giacomini INFN-CNAF School on Open Science Cloud Perugia, June 2017 https://baltig.infn.it/giaco/201706_perugia_cpp What is C++ C++ is a programming language that is:
More informationProfessor Terje Haukaas University of British Columbia, Vancouver C++ Programming
C++ Programming C++ code is essentially a collection of statements terminated by a semicolon, such as (spaces not needed): a = b + c; Most C++ code is organized into header files and cpp files, i.e., C++
More informationCSE 333 Midterm Exam Sample Solution 5/10/13
Question 1. (18 points) Consider these two C files: a.c void f(int p); int main() { f(17); return 0; b.c void f(char *p) { *p = 'x'; (a) Why is the program made from a.c and b.c incorrect? What would you
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationExceptions. CandC++ 7. Exceptions Templates. Throwing exceptions. Conveying information
Exceptions CandC++ 7. Exceptions Templates Stephen Clark University of Cambridge (heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford and Bjarne Stroustrup) Michaelmas
More information(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 7. Exceptions Templates 2/1. Throwing exceptions 14 }
Exceptions Some code (e.g. a library module) may detect an error but not know what to do about it; other code (e.g. a user module) may know how to handle it C++ provides exceptions to allow an error to
More informationCSCI 104 Templates. Mark Redekopp David Kempe
1 CSCI 104 Templates Mark Redekopp David Kempe 2 Overview C++ Templates allow alternate versions of the same code to be generated for various data types FUNCTION TEMPLATES 3 4 How To's Example reproduced
More informationGEA 2017, Week 4. February 21, 2017
GEA 2017, Week 4 February 21, 2017 1. Problem 1 After debugging the program through GDB, we can see that an allocated memory buffer has been freed twice. At the time foo(...) gets called in the main function,
More information