Brown Bag #2 Advanced C++. Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips.

Slides:



Advertisements
Similar presentations
Boost Writing better code faster with Boost. Boost Introduction Collection of C++ libraries Boost includes 52 libraries, 1.31 will have at least.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
Yaser Zhian Dead Mage IGDI, Workshop 10, May 30 th -31 st, 2013.
Chapter 12 Lists and Iterators. List Its an abstract concept not a vector, array, or linked structure. Those are implementations of a List. A list is a.
Brown Bag #3 Return of the C++. Topics  Common C++ “Gotchas”  Polymorphism  Best Practices  Useful Titbits.
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Vectors, lists and queues
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Introduction to the STL
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
. Templates. Example… A useful routine to have is void Swap( int& a, int &b ) { int tmp = a; a = b; b = tmp; }
COMP 171 Data Structures and Algorithms Tutorial 1 Template and STL.
Computer programming 1 Multidimensional Arrays, and STL containers: vectors and maps.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Standard Template Library C++ introduced both object-oriented ideas, as well as templates to C Templates are ways to write general code around objects.
Templates and the STL.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
STL Standard Template Library ● Good reference book: – The C++ Standard Library ● A Tutorial and Reference ● by Nicolai M. Josuttis ● 1999 – Addison Wesley.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
Templates Mark Hennessy Dept Computer Scicene NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
CS212: Object Oriented Analysis and Design Lecture 24: Introduction to STL.
Lecture 8-3 : STL Algorithms. STL Algorithms The Standard Template Library not only contains container classes, but also algorithms that operate on sequence.
Templates & STL Stefan Roiser, Lorenzo Moneta CERN PH/SFT.
Overview of C++ Templates
1 Chapter 1 C++ Templates Sections 1.6 and Templates Type-independent patterns that can work with multiple data types –Generic programming –Code.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
Templates Where the TYPE is generic. Templates for functions Used when the you want to perform the same operation on different data types. The definition.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Lecture 7.  There are 2 types of libraries used by standard C++ The C standard library (math.h) and C++ The C++ standard template library  Allows us.
1 Chapter 1 C++ Templates Readings: Sections 1.6 and 1.7.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
Vectors the better arrays. Why Vectors l vectors are implemented as a class (a template to be exact) l they serve the same purpose as arrays but using.
Generic Programming and Library Design Brian Bartman
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Templates Linked Lists.
Motivation for Generic Programming in C++
C++ Lesson 1.
C++ Templates.
Lecture 7-2 : STL Iterators
Exceptions, Templates, and the Standard Template Library (STL)
Templates.
Lecture 7-2 : STL Iterators
Vectors the better arrays.
CMSC 202 Lesson 22 Templates I.
Namespaces How Shall I Name Thee?.
CSE 303 Lecture 25 Loose Ends and Random Topics
Lecture 8-2 : STL Iterators and Algorithms
Templates I CMSC 202.
Lesson 25 Miscellaneous Topics
CMSC 341 C++ and OOP.
Vectors the better arrays.
Presentation transcript:

Brown Bag #2 Advanced C++

Topics  Templates  Standard Template Library (STL)  Pointers and Smart Pointers  Exceptions  Lambda Expressions  Tips and Tricks!

Templates  Generic code that works with many data types  Encourages code reuse  Turing-complete  Template metaprogramming (not covered)  Beware scary compiler/linker errors

Function Templates  A family of functions  Uses a generic type  On demand compilation  Compiler can deduce types  Type-safe int Square(int num) { return num * num; } template T Square(T num) { return num * num; } float result = Square(5.0f); int result = Square(2);

Class Templates  Explicit type specification  Declaration + implementation in same file  Can template methods not just whole classes  Great for containers template class Thing { public: Thing(T data) : m_data(data) {} T GetData() const { return m_data; } private: T m_data; }; Thing myThing = Thing (50); int data = myThing.GetData();  class and typename are interchangeable

Standard Template Library (STL)  Containers  vector  list  map  string  Algorithms  for_each  find  sort  Iterators  auto keyword (not directly relevant, but handy)

vector  Dynamic array  Access item at index = constant time  Iterate over all elements = linear time for ( auto iter = myVector.begin(); iter != myVector.end(); ++iter ) { iter->foo(); } std::vector myVector; std::vector ::iterator myVector[0].foo();

for_each #include using namespace std; void myFunction (int i) { cout << " " << i; } int main() { vector myVector; myVector.push_back(10); myVector.push_back(20); for_each (myVector.begin(), myVector.end(), myFunction); }

string  Special container type – sequence of characters.  Contains useful functions and common STL container functionality. #include int main() { std::string test(“Hello World!”); std::cout << “Length of string is “ << test.size() << “.\n”; // 12 }

map  Associative container that stores values as a pair.  An array uses an integer as the key type.  Each element must have a unique key.  Map containers support iterators that return key and value. #include using namespace std; int main() { map testMap; testMap.insert(map ::value_type(“Hello”, 5); int myInt = testMap[“Hello”]; cout << “Value contained in element with key ‘Hello’ is “ << myInt << “.\n”; // 5 }

Pointers  Pointers are references to memory blocks which contain data (or an instruction).  We access this data using the reference (&) and dereference (*) operators.

Dereference Operator (*)  If a pointer is a memory address, how do we access the object at that location?  Dereference a pointer to obtain the value at the memory address.

Reference Operator (&)  How do we alter a value at a given memory address and not just a copy?  Use the Reference operator to obtain a variable's memory address.

Pointer to a Pointer  It is possible to have a pointer that points to another pointer.

Pointer to a Pointer  Ever seen a DirectX function where you pass in a reference to a pointer? Check the argument list - that's what is happening there!

Class and Struct Pointers  You can create pointers to struct and class objects using the 'new' keyword:  Lets try setting the value of ack::bar to 5:

Class and Struct Pointers  This is C# syntax - doesn't work in C++!

The -> Operator  Like before, we must dereference the pointer before we can access the object!  There's a nicer way:  The -> operator dereferences a class or struct pointer and gives access to its members.  This is known as "syntactic sugar".

‘delete’ and Null Pointers  When you de-allocate a pointer using the 'delete' keyword, it is common to set the pointer's value to 0:  A pointer whose value is 0 is known as a null pointer.

Smart Pointers  These can be found in the Standard Library as part of the header file.  There are three types:  unique_ptr  shared_ptr  weak_ptr

Smart Pointer Syntax  Pointers declared using template-style syntax:  * and & operators can be utilised as normal:  Memory is de-allocated at the end:  However, de-allocation does not need to be done manually!

Reference Counting  Smart pointers count the number of references to an object in memory.  When a pointer leaves scope, the reference count is decremented.  When the reference count reaches 0, the memory is de-allocated.

unique_ptr  Allows for only one reference to a stored object - it is unique.  This is an invalid operation. However, ownership can be transferred:  When memory is de-allocated:

shared_ptr  shared_ptrs allow for multiple pointers to reference the same memory address.

weak_ptr  To avoid circular references, we use weak_ptrs:  In order to access the shared_ptr, we use weak_ptr::lock():  When the shared_ptr is deallocated, weak_ptr::lock() will return an empty shared_ptr object:

nullptr  Traditionally, a null pointer is defined as NULL, or 0. Consider the following:  How do we distinguish between 0 and a null pointer?  C++11 introduces the nullptr type:  Now we no longer need to worry about confusing null pointers and int values!

Smart Pointers: Summary  Smart pointers allow for all the same functionality of a standard pointer.  Makes use of Reference Counting for automatic de-allocation.  unique_ptr makes it easier to store single references to objects at a time.  shared_ptr allows for multiple pointers to share memory.  weak_ptr allows for accessing shared_ptr objects with easy clean-up.  nullptr helps to clearly distinguish from numeric values.

Simples!

Exceptions  Handle exceptional runtime errors  Unwinds stack (releases local variables, etc.)  Used by standard library / STL  Standard exceptions (bad_alloc, bad_cast, etc.)  Custom exceptions (extend std::exception )  Exception specifications try { throw 20; } catch (int e) { cout << “Exception:" << e << endl; } float foo(char param) throw (int);

Exceptions: The Good  Cleaner than error codes  Much nicer for deeply-nested functions  Separates error-handling from program flow  User-definable to carry detailed information  Catch constructor errors

Resource Acquisition Is Initialization (RAII)  Only destructors are guaranteed to run after an exception is hit  Use destructors to prevent resources leaks  Doesn’t require messy try/catch blocks void foo(void) { std::unique_ptr myThing( new Thing() ); myThing->Something(); }

Exceptions: The Bad, The Ugly  Multiple program exit points  Changes program flow, maybe harder to debug  Make debugger break on exceptions in Debug  Potential to leak resources if misused  Use smart pointers, etc. to avoid  Exception-safe code can be hard to write  Don’t throw in destructors  Only throw on exceptional errors  Hard to introduce to existing code

Lambda Expressions [ ] () mutable throw() –> int { }  Related to the concept of anonymous functions.  Helps to solve the problems of function objects and function pointers.  Function pointer has minimal syntactic overhead but does not retain state.  Function object retains state but requires the overhead of a class definition.  Lambdas feature minimal overhead and can retain state within the scope in which they are defined.

Lambda Expressions: Example void LambdaExample() { auto myLambda = [](int x, int y) -> int { return (x * 2) + y; }; int a = 3; int b = 4; int c = myLambda(a, b); std::cout << “The value of c is “ << c << “.\n”; // 10 int d = myLambda(c, b); std::cout << “The value of d is “ << d << “.\n”; // 24 }

Lambda Expressions: Syntax  Capture Clause: [ ]  Used to access variables from the scope enclosing the lambda.  Can be passed by reference or value (e.g. &x, y).  Default capture mode can be specified using & or = at the beginning for reference or value captures respectively (e.g. [&, x] or [=, y]).  ‘this’ pointer provides access to member variables of the enclosing class (e.g. [this]).  Parameter List: ()  Specifies the parameters passed into the function, as with a regular function declaration.  Mutable Specification: mutable  Allows values captured by reference to be modified within the function.  Will not change the original value, only the local copy.

Lambda Expressions: Syntax (cont.)  Throw Specification: throw()  Specifies if the lambda can throw an exception.  throw() specifies no exception can be thrown.  throw(T) specifies an exception of type T can be thrown.  Return Type: -> T  Follows trailing return-type syntax introduced in C++11.  Explicitly specifies the return value of the function.  Can be implicitly implied via a return statement in the function body.  Function Body: { }  Defines the instructions to be performed, as with a standard function.

Lambda Expressions: Example Revisited void LambdaExample() { auto myLambda = [](int x, int y) -> int { return (x * 2) + y; }; int a = 3; int b = 4; int c = myLambda(a, b); std::cout << “The value of c is “ << c << “.\n”; // 10 int d = myLambda(c, b); std::cout << “The value of d is “ << d << “.\n”; // 24 }

Why use Lambda Expressions?  Iterator functions: #include int main() { std::vector myVector; myVector.push_back(10); myVector.push_back(20); int totalCount = 0; for_each (myVector.begin(), myVector.end(), [&totalCount](int x) { totalCount += x; }); std::cout << “The total of all values in myVector is “ << totalCount << “.\n”; // 30 }

Why use Lambda Expressions?  Asynchronous tasks: #include using namespace Concurrency; int main() { auto doubleNum = [](int x) { return x * 2; }; auto incrementNum = [](int x) { return ++x; }; auto startTask = create_task([]() -> int { return 5; }); int finalNum = startTask.then(doubleNum).then(incrementNum).then(doubleNum).get(); std::cout << “The value of finalNum is “ << finalNum << “.\n”; // 22 }

Tips and Tricks

Const FTW  Prefer pass-by-reference-to-const to pass-by-value (item #20)  Avoid unnecessary constructors/destructor calls  Still guarantee to caller that object won’t be changed void Foo( const Thing& input ); Thing GetData() const;  const member functions (getters)

Enums FTW struct MyEnum { enum Enum { MAX }; enum class MyEnum { MAX };  Nicer and safer than pre-processor definitions  Enum classes/structs (C++ 11)  Old: Wrap Enums in struct  Now type-safe in C++ 11

Further Reading  Microsoft Developers Network (MSDN)  CPlusPlus.com