Introduction to Effective C++ Programming Kwang Hee Ko December 6, 2010 Modeling and Simulation Laboratory School of Mechatronics Gwangju Institute of.

Slides:



Advertisements
Similar presentations
Object Oriented Programming Lect. Dr. Daniel POP Universitatea de Vest din Timişoara Facultatea de Matematică şi Informatică.
Advertisements

Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Standard Template Library (STL) Overview – Part 1 Yngvi Bjornsson.
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Templates and the STL.
Lecture 23 Today Standard Template Library Programs in: programs/p19 Bibliography: Textbook p.252,
Object Oriented Data Structures
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Writing Your Own STL Container Ray Lischner
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Introduction to Effective C++ Programming Kwanghee Ko Design Laboratory Department of Ocean Engineering Massachusetts Institute of Technology Day 3.
Review for Midterm Chapter 1-9 CSc 212 Data Structures.
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
STL !!!generic programming!!! Anar Manafov
Data Structures Using C++ 2E
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
LECTURE LECTURE 17 More on the Standard Template Library 23 A guided tour with common examples of the containers.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
SNU OOPSLA Lab. Chap17. Standard Containers © copyright 2001 SNU OOPSLA Lab.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
Templates ©Bruce M. Reynolds & Cliff Green1 C++ Programming Certificate University of Washington Cliff Green.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Lists Chapter 8. 2 Linked Lists As an ADT, a list is –finite sequence (possibly empty) of elements Operations commonly include: ConstructionAllocate &
Lecture 11 Standard Template Library Lists Iterators Sets Maps.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Lecture 7 : Intro. to STL (Standard Template Library)
A gentle introduction to the standard template library (STL) Some references:
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Effective C++, 2nd Ed. By Scott Myers. Constructors, Destructors, and Assignment Operators 11.Define a copy constructor and an assignment operator for.
1 STL Containers Copyright Kip Irvine, All rights reserved. Only students enrolled in a class at Florida International University may copy or print.
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
The Standard Template Library Container Classes Version 1.0.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
7. Inheritance and Polymorphism
Standard Template Library (STL)
STACKS AND QUEUES UNIT 2 DS THROUGH C++.
Collections Intro What is the STL? Templates, collections, & iterators
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
ADT Implementations: Templates and Standard Containers
CISC/CMPE320 - Prof. McLeod
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
Chapter 3 Lists, Stacks, and Queues
Presentation transcript:

Introduction to Effective C++ Programming Kwang Hee Ko December 6, 2010 Modeling and Simulation Laboratory School of Mechatronics Gwangju Institute of Science and Technology

Introduction Don’t have be a “C++ language lawyer” to design a good class. But there do exist rules to follow!!!

References T. Cargill, C++ Programming Style, Addison-Wesley, New York, T. Cargill, Exception Handling: A False Sense of Security. C++ Report, 6(9):21-24, J. Coplien, Advanced C++: Programming Styles and Idions, Addison-Wesley, New York, M. A. Ellis and B. Stroustrup, The Annotated C++ Reference Manual, Addison-Wesley, New York, S. Meyers, More Effective C++: 35 New Ways to Improve Your Programs and Designs, Addison-Wesley, New York, S. Meyers, Effective C++: 50 Specific Ways to Improve Your Programs and Designs, Addison-Wesley, New York, 2 nd Edition, R. Murray, C++ Strategies and Tactics, Addison-Wesley, New York, B. Stroustrup, The C++ Programming Language, Addison-Wesley, New York, 3 rd Edition, 1997.

Terms Declaration vs. definition Default constructor (default) copy constructor Initialization vs. assignment Inheritance, polymorphism, OOP, etc.

General Guidelines Develop your code under at least two compilers. Improve your understanding of C++. Familiarize yourself with the standard library (STL). Prefer compile-time and link-time errors to runtime errors. Pay attention to compiler warnings. Ensure that non-local static objects are initialized before they are used. Know what functions C++ silently writes and calls.

Minimize “C habits” in your C++ Program Prefer const and inline to #define. Prefer iostream to stdio.h. Prefer new/delete to malloc/free. Prefer C++ style comments.

Take Good Care of Memory Management Use the same form in corresponding uses of new and delete. Use delete on pointer members in destructors. Be prepared for out-of-memory conditions. Adhere to convention when overloading operator new and operator delete. Avoid hiding the normal form of new. Overload operator delete if you overload operator new.

Understanding The Standard Template Library Containers – A container is an object that holds other objects. You can add objects to a container and remove objects from it. Standard Library Algorithms Iterators and Allocators – Iterators : They provide an abstract view of data. They are an abstraction of the notion of a pointer to an element of a sequence. The element currently pointed to : *, -> operations Point to next element : ++ Equality : == – Allocators : They are used to insulate container implementations from details of access to memory.

Containers : one-dimensional array : doubly-linked list : double-ended queue : queue – queue, priority queue : stack : associative array – Map, multimap : set – Set, multiset : set of booleans

General Info. Sequences – Adapters –

Example : Vector 1 (Use of []) #include using namespace std; int main(void) { vector v(5); int i; for(i=0;i<5;i++) { v[i] = i; cout << v[i] << endl; } int sum=0; for(i=0;i<5;i++) sum += v[i]; cout << "Sum : " << sum << endl; }

Example : Vector 2 (Use of Iterators) #include using namespace std; int main(void) { vector v(5); int sum; vector ::iterator first = v.begin(); vector ::iterator last = v.end(); sum = 0; while(first != last) { sum += *first; cout << *first << endl; ++first; } cout << "sum : " << sum << endl; }

Example : Vector 3 (Stack Operation) #include using namespace std; int main(void) { vector v(5); int sum; v.push_back(100); vector ::iterator first = v.begin(); vector ::iterator last = v.end(); sum = 0; while(first != last) { sum += *first; cout << *first << endl; ++first; } cout << "sum : " << sum << endl; }

Example : Vector 3 (Various Operations) vector v(5); v.push_back(100); // increase the size of v by one v.pop_back(); // decrease the size by one v.back() // extract the last object. v.erase(iterator); v.insert(iterator,int); // insert int after what iterator points to v.size() // current size v.capacity() // v.max_size() //

Example : List (Use of Iterators) No subscripting : operator[] Bidirectional iterator Additional operations – splice, merge, front, push_front, pop_front – sort, unique

Example : List (Use of Iterators) #include using namespace std; int main(void) { list v(5); int sum; list ::iterator first = v.begin(); list ::iterator last = v.end(); sum = 0; while(first != last) { sum += *first; cout << *first << endl; ++first; } cout << "sum : " << sum << endl; }

#include using namespace std; typedef list List; typedef list ListofList; void print_list(const List& list1, int id); int main(void) { ListofList listoflist1; for(int i=0;i<3;i++) { List list1; for(int j=0;j<4;j++) list1.push_back(i*4 + j); listoflist1.push_back(list1); } ListofList::iterator it = listoflist1.begin(); ListofList::iterator ie = listoflist1.end(); for(int j=1;it != ie; ++it,++j) { const List &list1 = *it; print_list(list1,j); } return 0; } Example : List of List 1

Example : List of List 2 void print_list(const List& list1, int id) { cout << "list " << id << " : "; List::const_iterator ils = list1.begin(); List::const_iterator ile = list1.end(); while(ils != ile) cout << *ils++ << ' '; cout << endl; }

Example : Stack #include using namespace std; int main(void){ stack s; s.push("banana"); s.push("apple"); cout << s.top() << " " << s.size() << endl; s.pop(); cout << s.top() << " " << s.size() << endl; s.pop(); return 0; }

Example : Queue & Priority_Queue #include using namespace std; int main(void){ queue s; s.push("banana"); s.push("apple"); cout << s.front() << " " << s.size() << endl; s.pop(); cout << s.front() << " " << s.size() << endl; s.pop(); priority_queue k; k.push(56); k.push(2); k.push(100); k.push(5); cout << k.top() << endl; k.pop(); cout << k.top() << endl; return 0; }

Associative Containers map : a single value is associated with each unique key. multimap : an associative array that allows duplicate elements for a given key. set, multiset : degenerate associative arrays in which no value is associated with a key.

map A sequence of (key, value) pairs that provides for fast retrieval based on the key. Each key in a map is unique. It provides bidirectional iterators hash_map : useful for a case that there is no need to keep the container sorted.

Example : map #include using namespace std; int main(void){ map salary; salary["Steve"] = 2000; salary["Tom"] = 3000; salary["John"] = 4500; salary["Neal"] = 3000; salary["Jane"] = 4000; int total = 0; typedef map ::const_iterator CI; for(CI p = salary.begin(); p!=salary.end(); ++p) { total += p->second; cout first second << '\n'; } cout << " \n total \t" << total << endl; cout << "Tom's salary : " << salary["Tom"] << endl; cout << "Jane's salary : " << salary.find("Jane")->second << endl; return 0; }

Algorithms STL provides algorithms to serve the most common and basic needs. Most algorithms operate on sequences using iterators and values. Function objects – Useful when we want the algorithms to execute code that we supply.

Algorithms Example for function objects bool less_than_7(int v) { return v < 7; } Void f(list & c) { list ::const_iterator p = find_if(c.begin(),c.end(),less_than_7); }

Algorithms Find, for_each, count, copy, search, sort, binary search, etc.

General Guidelines Avoid returning “handles” to internal data. Avoid member functions that return non- const pointers or references to members less accessible than themselves. Never return a reference to a local object or to a dereferenced pointer initialized by new with in the function (memory leakage). Postpone variable definitions as long as possible.

General Guidelines Public inheritance models : “isa” relation? – Ex. A bus is a vehicle? Never redefine an inherited non-virtual function. Never redefine an inherited default parameter value. Avoid cast down the inheritance hierarchy. Model “has-a” or “is-implemented-in- terms-of” through layering.

General Guidelines Use multiple inheritance judiciously.

Ambiguities under Multiple Inheritance Case 1 Base 1 f(); g(); Base 2 f(); h(); Derived j(); k(); Derived d; d.g(); // OK d.h(); // OK d.f(); // Ambiguous!!! d.Base1::f(); // OK d.Base2::f(); // OK

Ambiguities under Multiple Inheritance Case 2 Left int y; Right int z; Bottom int a Top int x;

Ambiguities under Multiple Inheritance Case 2 Left int y; Right int z; Bottom int a Default inheritance mechanism -> maintains separate copies of the data members inherited from all base classes. Top int x;

Ambiguities under Multiple Inheritance Case 2 (Non-virtual Base class) Left int y; Right int z; Bottom int a Top int x; Top int x; Top int x; Top int x; Left int y; Right int z; Bottom int a

Ambiguities under Multiple Inheritance Case 2 : Virtual Base Class Left int y; Right int z; Bottom int a Top int x; virtual class Left::public virtual Top{…} class Right::public virtual Top{…} Top int x; Left int y; Right int z; Bottom int a

Ambiguities under Multiple Inheritance Case 2 : Virtual Base Class Left int y; Right int z; Bottom int a Top int x; virtual Inherently ambiguous!!! Ex) Bottom b; b.x -> b.Left::x? b.Right::x? b.Top::x?

Ambiguities under Multiple Inheritance Case 2 : Virtual Base Class Left int y; Right int z; Bottom int a Top int x; virtual Assignment for Top::x happens twice. - Bottom->Left->Top - Bottom->Right->Top

Ambiguities under Multiple Inheritance Case 2 : Virtual Base Class Left int y; Right int z; Bottom int a Top int x; virtual Assignment for Top::x happens twice. - Bottom->Left->Top - Bottom->Right->Top Solution???

General Guidelines Use multiple inheritance judiciously. Before using virtual base classes, understand them thoroughly. – Use an experimental program to understand its behavior. If a public base class does not have a virtual destructor, no derived class should have a destructor. If a multiple inheritance hierarchy has any destructors, every base class should have a virtual destructor.

General Guidelines Declare a copy constructor and an assignment operator for classes with dynamically allocated memory. Prefer initialization to assignment in constructors. List members in an initialization list in the order in which they are declared. Make sure base classes have virtual destructors. Have operator= return a reference to *this. Assign to all data members in operator=. Check for assignment to self in operator=. Overloading vs. default argument.

General Guidelines : Efficiency Don’t guess. Use an execution profiler to isolate performance problems. – g++ : use ‘–pg’. Then use ‘gprof’. – For Visual C++, use professional or enterprise editions Optimize your code as much as you can at a source level. – Optimization options (‘-O2’ in g++) provided by a compiler could be another choice. But it has limitation.

General Guidelines : Efficiency Consider using lazy evaluation. – Defer computations until the results of those computations are required. Understand the origin of temporary objects. – Implicit type conversion – Object return from a function Overload to avoid implicit type conversions. Facilitate the return value optimization. Consider using ‘op=’ instead of stand-alone ‘op’. – Provide both in your class. Consider alternative libraries.

Efficiency : Example First Design – Number of objects created : – Elapsed Time : 1.3 sec. int main(void) { Test_Int a(102); a.report(); cout << a << endl; for(int i=0;i<500000;i++) for(int j=0;j<10;j++) a = a + 1; a.report(); cout << a << endl; a.report(); }

int main(void) { Test_Int a(102); a.report(); const Test_Int one=1; cout << a << endl; for(int i=0;i<500000;i++) for(int j=0;j<10;j++) a = a + one; Efficiency : Example Second Design – Number of objects created : – Elapsed Time : a.report(); cout << a << endl; a.report(); }

int main(void) { Test_Int a(102); a.report(); const Test_Int one=1; cout << a << endl; for(int i=0;i<500000;i++) for(int j=0;j<10;j++) a = a + one; Efficiency : Example Second Design – Number of objects created : (67%) – Elapsed Time : 0.74 sec. (57%) a.report(); cout << a << endl; a.report(); }

int main(void) { Test_Int a(102); a.report(); const Test_Int one=1; cout << a << endl; for(int i=0;i<500000;i++) for(int j=0;j<10;j++) a += one; Efficiency : Example Third Design – Number of objects created : – Elapsed Time : a.report(); cout << a << endl; a.report(); } Test_Int Test_Int::operator+=(const Test_Int& t) { return a+=t.a; }

int main(void) { Test_Int a(102); a.report(); const Test_Int one=1; cout << a << endl; for(int i=0;i<500000;i++) for(int j=0;j<10;j++) a += one; Efficiency : Example Third Design – Number of objects created : (57%) – Elapsed Time : 0.43 sec. (58%) a.report(); cout << a << endl; a.report(); } Test_Int Test_Int::operator+=(const Test_Int& t) { return a+=t.a; }

Efficiency : Example Fourth Design – Number of objects created : – Elapsed Time : Test_Int& Test_Int::operator+=(const Test_Int& t) { add(t); return *this; } void Test_Int::add(const Test_Int& t) { a += t.a; }

Efficiency : Example Fourth Design – Number of objects created : 2 ( %) – Elapsed Time : 0.3 sec. (70%) Test_Int& Test_Int::operator+=(const Test_Int& t) { add(t); return *this; } void Test_Int::add(const Test_Int& t) { a += t.a; }

Efficiency : Example Fourth Design (relative to the first design) – Number of objects created : Almost nothing. – Elapsed Time : 23% Test_Int& Test_Int::operator+=(const Test_Int& t) { add(t); return *this; } void Test_Int::add(const Test_Int& t) { a += t.a; }

General Guidelines : Efficiency Understand the costs of virtual functions.