cs11 advanced c++ - caltech computing +...

20
CS11 Advanced C++ Spring 2018 – Lecture 1

Upload: doannguyet

Post on 27-Apr-2018

244 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

CS11 Advanced C++Spring 2018 – Lecture 1

Page 2: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Welcome to CS11 Advanced C++!

• A deeper dive into C++ programming language topics• Prerequisites:• CS11 Intro C++ track is strongly recommended (obvious)

• You should be familiar with:• Implementing C++ classes and functions / member-functions• Dynamic memory management and the RAII pattern• Basic use of the C++ standard library - strings, collection templates, threads,

stream IO and stream-based file IO• Pointers and references (not necessarily rvalue-references)• Basic operator overloading• Proper use of const keyword• Basic exception handling• Using tools like make and Doxygen

Page 3: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Assignments and Grading

• Each lecture has a corresponding assignment for exploring the material• Labs are due approximately one week later, at noon• e.g. this term labs will be due on Tuesdays at noon• Submit on csman

• Labs are given a 0..3 grade, meaning:• 3 = excellent (masters all important parts)• 2 = good (demonstrates mastery of key idea; a few minor issues)• 1 = insufficient (not passing quality; significant bugs that must be addressed)• 0 = incorrect (worthy of no credit)

• Must receive at least 75% of all possible points to pass the track• Can submit up to 2 reworks of assignments to improve grade• Not uncommon for initial submission to get a 0!• Don’t take it personally; it’s really not a big deal in CS11 tracks

Page 4: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Assignments and Grading (2)

• All code submitted is expected to be well documented and written in

a clean, uniform coding style

• Specifics are not as relevant to me; consistency is the most important thing

• Use Doxygen to generate documentation from C++ code

• doxygen -g to generate initial Doxyfile config-file

• Edit configuration file to generate HTML docs only, into a subdirectory

• doxygen should generate docs after that

• See http://www.stack.nl/~dimitri/doxygen/ for much more detail!

• Initially will use make for building projects…

• Hopefully will also include coverage of CMake later in the term

Page 5: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

C++ Compiler

• Can use g++/gdb or clang++/lldb for this track• Currently most of the instructions are written for GNU toolset• Feel free to contribute LLVM-related info along the way!

• Should be using C++14 for your implementations• Can ask the compiler what version of C++ is its default• g++ -dM -E -x c++ /dev/null | grep cplusplus#define __cplusplus 201402L• clang++ -dM -E -x c++ /dev/null | grep cplusplus#define __cplusplus 199711L

• Can tell the compiler what version of C++ to use (recommended!)• g++ -std=c++14 ...• clang++ -std=c++14 ...• Or, in Makefiles (recommended!): CXXFLAGS = -std=c++14

Page 6: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

First Labs: Implement C++ Vector Template

• First few labs will focus on implementing a C++ vector template• Like std::vector, but called ::Vector• Provides a good overview of how the STL does its thing• Also gives opportunity to use some more advanced C++ facilities

• Lab 1: Implement the basic Vector growable-array functionality• Growable array – has both size (actual number of elements) and capacity

(amount of space available for elements)• Vector allocates more memory than is strictly required, so that appending is

O(1) (amortized over many append operations)• No iterators, no move operations – will add these in the next assignment

• A good review of:• How to declare templates• Basic memory management, the RAII pattern, and smart pointers• const correctness• Operator overloading

Page 7: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

C++ Templates

• Very common to have classes/functions that are independent of typeclass Point {

int x, y;public:

Point(int x, int y) : x(x), y(y) { }int getX() const { return x; }int getY() const { return y; }void setX(int x) { this->x = x; }void setY(int y) { this->y = y; }

};

• What about using float, double, std::complex, etc. for coordinates?

Page 8: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

C++ Templates (2)

• Can turn our Point class into a templatetemplate <typename T>class Point {

T x, y;public:

Point(T x, T y) : x(x), y(y) { }T getX() const { return x; }T getY() const { return y; }void setX(T x) { this->x = x; }void setY(T y) { this->y = y; }

};

• Now, can instantiate our template with different coordinate typesPoint<int> p1{5, 2};Point<double> p2{3.3, -1.4};

Page 9: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

C++ Templates (3)

• Recall: The template is not a class! The template can be used to instantiate classes, once the missing details are specified.• The Point class-template is a pattern for making classes.• Point<int> is a class instantiated from the Point template, with T = int.• Often: “A class template can be instantiated to make a template class.” ICK.

• The compiler must see the entire template specification before it can be instantiated by code

• Consequence: templates are usually specified entirely in .h files; no corresponding .cpp file to go with it• No separation of declaration and definition, as is usually the case in C++• If a template is only for use within one .cpp file, the template may be

specified at the top of that file

Page 10: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Dynamic Memory Management

• Myth: It’s hard to manage dynamic memory in C++ programs• Used to be much more accurate, but modern C++ has developed many

techniques for simplifying dynamic memory management• Nowadays, it should be easy to manage memory in C++ programs, if you use

all the available tools

• The RAII pattern:• Resource Acquisition [or Allocation] Is Initialization

• Create an object that wraps a dynamically allocated resource• The object’s sole purpose is to manage one resource

• At construction, the object either allocates the resource, or it assumes ownership of the resource• A failure to allocate causes initialization to fail, usually with an exception

• At destruction, the object deallocates the resource (if appropriate)• Resource management is tied to an object’s lifecycle

Page 11: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Dynamic Memory Management (2)

• “Smart pointers” are a very common implementation of this RAII approach• The smart-pointer object holds a pointer to dynamically allocated memory

• Typically, allocation occurs as part of smart-pointer initialization• Through operator-overloading, the smart-pointer is able to “act like” a pointer,

through overloading of * and -> operators.• C++11 Standard Library introduced two smart-pointer classes (originally

developed as part of the Boost library)• std::shared_ptr<T> is a multiple-ownership smart pointer for when

dynamically-allocated memory is shared by multiple parts of a program• Manages a T*, allocated with “new T(…)”

• std::unique_ptr<T> is a single-ownership smart pointer for when dynamically-allocated memory is used by only one part of a program• Also manages a T*, allocated with “new T(…)”

• #include <memory> to use these smart-pointers

Page 12: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Dynamic Memory Management (3)

• shared_ptr<T> uses reference-counting to keep track of how many parts of the program reference a pointer• Reference-counting imposes a (slight) time and space overhead

• unique_ptr<T> assumes it is sole owner of the referenced memory• No reference-counting overhead• Only one unique_ptr may point to a given T*

• Use unique_ptr<T> when only one part of your program will ever need to access/manage a dynamically allocated chunk of memory• e.g. managed by a single function, or by a single object• (A good choice for our ::Vector class-template)

• Use shared_ptr<T> when several parts of your program will need to access/manage a dynamically allocated chunk of memory• e.g. if multiple objects need to access / manage a single chunk of memory• (e.g. if you were implementing a tree or a graph data structure)

Page 13: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Default Constructors and Operators

• Every class provides certain common operations

• (…unless those operations are deleted – C++11)

• Example: copy constructor• Widget(const Widget &w)

• All of w’s members are copied into the new object being initialized

• Usually, w is not changed by performing the copy

• Widget w{…};Widget w2{w}; // Uses the copy constructor• Default implementation copies all members of an existing object into a new

object (a shallow copy)

• Copy-constructor is used for passing object-arguments by value, etc.

Page 14: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Default Constructors and Operators (2)

• Every class provides certain common operations• (…unless those operations are deleted – C++11)

• Example: copy-assignment operator• Widget & operator=(const Widget &w)

• All of w’s members are copied into the target of the assignment• (Previous contents of the object are cleaned up, if necessary)• Usually, w is not changed by performing the copy-assignment

• Widget w, w2;w2 = w; // Uses the copy-assignment operator• Default implementation copies all members of the RHS to the LHS• Default implementation also does not test for self-assignment, e.g.w = w;

Page 15: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Default Constructors and Operators (3)

• These default implementations can break objects that dynamically allocate memoryclass FloatArray {

int num_elems;float *elems;

public:FloatArray(int n) : num_elems{n} { elems = new float[n]; }~FloatArray() { delete[] elems; }float get(int index) const { return elems[index]; }void set(int index, float value) { elems[index] = value; }

};• (Note: Should use std::unique_ptr<float[]> instead!)

• Will the default copy-constructor or copy-assignment operator work with this class?• No: will end up with multiple objects referencing the same array of

elements

Page 16: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Default Constructors and Operators (4)

• Need to implement a copy-constructor and a copy-assignment operator for this classclass FloatArray {

int num_elems;float *elems;

public:FloatArray(int n) : num_elems{n} { elems = new float[n]; }~FloatArray() { delete[] elems; }float get(int index) const { return elems[index]; }void set(int index, float value) { elems[index] = value; }

};• Make a deep copy of the array of elements held by the object

• Example copy constructor, makes a deep copy of the elements:FloatArray(const FloatArray &f) {

num_elems = f.num_elems;elems = new float[num_elems];for (int i = 0; i < num_elems; ++i)

elems[i] = f.elems[i];}

Page 17: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

The Rule of Three

• Very good idea to follow the Rule of Three• If your class implements a custom copy-constructor, a custom copy-

assignment operator, and/or a custom destructor, it should probably implement all three.• Copy-initialization and copy-assignment are very closely related

• Note 1: If you manage dynamically-allocated resources with smart pointers, you won’t actually need a custom destructor• The smart-pointer object will take care of deletion for you• Really only need a custom copy-constructor and a custom copy-assignment

operator

• Note 2: Rule of Three was most relevant up until C++11, when move semantics were introduced• Going forward from C++11, we have the Rule of Five, which includes both

copying and moving objects• Will talk more about the Rule of Five in the future

Page 18: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Operator Overloading and Array Indexing

• Since vectors are growable arrays, it’s useful to support array-indexing operator []Vector<int> v{10};v[2] = 15;cout << v[8] << '\n’;

• Implement this operator overload for non-const usage:T & Vector::operator[](int index)• Implementation must return a reference to the element being accessed, so

that it can be the target of an assignment• Specifically, cannot return a copy of the element’s value, or else assignment

to the element will not work• C++ requires this to be implemented as a member operator-overload• i.e. a member-function of the Vector class-template

Page 19: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Operator Overloading and Array Indexing (2)

• Want to support const usage of vectors as well!template <typename T>void printVector(const Vector<T> &v) {

for (int i = 0; i < v.size(); ++i)cout << ' ' << v[i];

}

• Must provide a second version of this operator for const usage:const T & Vector::operator[](int index) const• Again, implementation must return a reference to the element being

accessed• (Reasons have to do with iterators, which we will talk about next time!)

• Again, C++ requires this to be implemented as a member operator-overload

Page 20: CS11 Advanced C++ - Caltech Computing + …courses.cms.caltech.edu/cs11/material/advcpp/lectures/cs...Welcome to CS11 Advanced C++! •A deeper dive into C++ programming language topics

Member / Non-Member Operator Overloads

• These operators must be member operator overloads:operator= (assignment)operator() (function invocation)operator[] (indexing)operator-> (member access)

• Some operators must be non-member operator overloads:istream & operator>>(istream &, T &v)ostream & operator<<(ostream &, const T &v)

• istream and ostream classes are in C++ Standard Library; cannot change them!

• If an operator must support mixed types, must be non-member:const Rational operator+(const Rational &lhs, int rhs);const Rational operator+(int lhs, const Rational &rhs);• Allows both int + Rational and Rational + int usage

• In general, you should prefer non-member operator overloads, unless you have to violate encapsulation in gross ways to support it