C++ Modern and Lucid C++ for Professional Programmers
|
|
- Rosamond Jennings
- 5 years ago
- Views:
Transcription
1 Informatik C++ Modern and Lucid C++ for Professional Programmers part 13 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2017
2 main(argc,argv) Arrays & Pointer passing arguments to C++ programs dealing with legacy data structures To be avoided!
3 Passing Program Arguments int main(int argc, char *argv[]) array of pointers to char representing strings As with many other languages you can pass command-line arguments to a C++ program Mechanism is inherited from C uses pointers and array argument require separate element counter (as all C arrays) char * represents a string in C char sequence terminated by '\0' 3
4 "Naked" Arrays as parameters int main(int argc, char *argv[]) Defining a function parameter as array means just passing a naked pointer to the first element array dimension is lost int main(int argc, char **argv) -> use std::array or vector in own code You either need to pass the dimension separately (argc) or have other means to know the sequence end (e.g., '\0' terminating a C string) or use a template function deducing the type soon: span/view(c++20) and string_view(c++17) 4
5 Pointers to Arrays are Random-access Iterators int main(int argc, char *argv[]){ copy(argv+1, argv+argc, std::ostream_iterator<std::string>{std::cout,"-"); Array parameters are naked pointers p = first element, p+dimension=past-the-end implementation of echo program they work like random access iterators ++p, *p, p+int, p[int], *(p+int) also int[p] syntactically possible -> confusion! 5
6 Initializing an Array int five[5]{; int four[4]={1,2,3,4; double d[4]{1.0, 2.0,; double m[2][3]{{1,2,3,{4,5,6; Arrays get a dimension = number of elements 5 zeros d[2]==d[3]==0.0 arrays without initializer might be uninitialized Missing initializer values -> default value multi-dimensional arrays are possible int x[5][6] -> x is array of 5 elements that are arrays of 6 elements of type int x[1,2] -> possible but wrong -> x[2]! (comma operator) 6 char s[6]{"hello"; 5 chars + '\0'
7 comma operator,()? what does that mean? double m[2][3]{{1,2,3,{4,5,6; m[0,1]; Caution: multi-dimensional index access requires all brackets to be present: m[0][1] using a comma is syntactically correct (comma operator): a, b, means sequential evaluation of sub-expressions usually only useful if first part has a side effect one can even overload operator,(a, b) which looses the sequential evaluation property 7
8 Deducing Array Dimensions template <typename T, unsigned N> void printarray(std::ostream &out, T const (&x)[n]){ copy(x, x+n, std::ostream_iterator<t>{out,", "); () are needed Passing an array type by reference in a template function allows dimension deduction by template argument deduction T (&x)[n] could just have N deduced if array element type is fixed Initializing an array will deduce dimension from the number of initialized elements int a[]={1,2,3; int a[3] printarray(std::cout,a); char str[]="world"; char str[6] 8
9 Summary "naked" Arrays Don't use naked arrays -> refactor to std::array one exception: program arguments of main() There are no dynamically sized arrays in C++, use vector Arrays degenerate to a naked pointer when passed as function argument then you always need to pass the length as well! C++20 will have std::span/std::view as array references Pointers to arrays work like random-access iterators ptr+dimension = end iterator 9
10 Dynamic Heap Memory Management new/delete, std::unique_ptr<t>, std::shared_ptr<t>
11 Heap Memory always rely on library classes for managing it (RAII) might be needed for creating object structures first think about library classes for your intended structure Look into the Boost library collection if std is insufficient for polymorphic factory functions to class hierarchies if you return a base-class "pointer" to one of its subclasses from functions 11
12 C++ heap memory basics: DO NOT! auto ptr=new int{5; std::cout << *ptr << '\n'; delete ptr; NEVER DO THIS C++ allows allocating objects on the heap auto ptr=new Type{argument; However, if done manually you are responsible for deallocation and risk undefined behavior: memory leaks dangling pointers double deletes no garbage collection happens, you must delete or leak 12
13 C++ heap memory real usage std::unique_ptr<x> factory(int i){ return std::make_unique<x>(i); Never-ever use plain pointers with heap allocation in modern C++ std::unique_ptr<t> obtained with make_unique<t> std::shared_ptr<t> obtained with make_shared<t> Never come to a situation where you have to explicitly "delete ptr;" (or generate a memory leak!) Always prefer local (stack-based or member) value-type variables over manually heap-allocated pointers. 13
14 std::unique_ptr<t> Used for unshared heap memory or for local stuff that must be on the heap this is a very very rare need, e.g., very large instances with limited stack space can be returned from a factory function only one owner! can wrap to-be-freed pointers from C functions when interfacing legacy code not best for class hierarchies, use std::shared_ptr<base> instead (unique_ptr base classes need virtual destructor) 14
15 No More "naked" Pointers: Resource Management with unique_ptr<t> it is guaranteed to be a Highlander: "There can be only one!" - no second reference #include <memory> transfer of ownership through return by value #include <iostream> std::unique_ptr<int> afactory(int i){ return std::make_unique<int>(i); int main(){ auto pi=afactory(42); std::cout << "*pi =" << *pi << '\n'; std::cout << "pi.valid? "<< std::boolalpha true << static_cast<bool>(pi) << '\n'; auto pj=std::move(pi); std::cout << "*pj =" << *pj << '\n'; transfer of ownership from lvalue std::cout << "pi.valid still? " << static_cast<bool>(pi) << '\n'; false 15
16 std::unique_ptr<t> for C pointers some C functions return pointers that must be deallocated with the function ::free(ptr) We can use unique_ptr to ensure that cxa_demangle() is such a function (compiler-specfic) std::string demangle(char const *name){ std::unique_ptr<char,decltype(&::free)> tobefreed{ cxxabiv1:: cxa_demangle(name,0,0,0),&::free; std::string result(tobefreed.get()); return result; Even when there would be an exception, free will be called on the returned pointer, no memory leak! 16
17 std::unique_ptr<t> for C pointers A unique_ptr storing the address of free() has an extra pointer and thus is twice the size. struct free_deleter{ template <typename T> void operator()(t *p) const { std::free(const_cast<std::remove_const_t<t>*>(p)); ; template <typename T> using unique_c_ptr=std::unique_ptr<t,free_deleter>; Better provide a deleter type as template argument no space overhead! inline std::string plain_demangle(char const *name){ if (!name) return "unknown"; unique_c_ptr<char const> tobefreed {abi:: cxa_demangle(name,0,0,0); std::string result(tobefreed?tobefreed.get():name); return result; 17
18 Guidelines for unique_ptr as member variable: to keep a polymorphic reference instantiated by the class or passed in as unique_ptr and transferring ownership as local variable: to implement RAII Resource Acquisition Is Initialization can provide custom "deleter" functor as second template argument to type that is called on destruction (see ::free usage) std::unique_ptr<t> const p{new T{; //local can not transfer ownership -> can not leak! 18
19 shared_ptr<t> + make_shared<t>() #include <memory> unique_ptr allows only one owner and can not be copied, only returned by value shared_ptr works more like Java's references, it can be copied and passed around and the last one ceasing to exist deletes the object You create shared_ptr and associated objects of type T using std::make_shared<t>(...) make_shared<t> allows all T's public constructor's parameters to be used 19
20 What is it for? If you really need heap-allocated objects, because you create your own object networks you can use shared_ptr<t> If you need to support run-time polymorphic container contents or class members that can not be passed as reference, e.g., because of lifetime issues Factory functions returning shared_ptrs for heap allocated objects but first check if alternatives are viable: (const) references as parameter types or class members (to surviving objects!) plain member objects or containers with plain class instances 20
21 No More "naked" Pointers: Resource Management with shared_ptr<t> If you really need to keep something explicit on the heap, use a factory like that: #include <memory> // or <boost/shared_ptr.hpp> #include <string> struct A{ A(int a,std::string b, char c){ ; example usages: int main(){ auto an_a=a_factory(); auto A_factory(){ return std::make_shared<a>(5,"hi",'a'); auto b=an_a; // second pointer to same object A c{*b; // copy ctor. auto another = std::make_shared<a>(c); // copy ctor on heap 21
22 No More "naked" Pointers: Class hierarchies with shared_ptr<t> use std::ostream, just as an example for a base class and a very primitive factory function, need to use concrete type with make_shared std::shared_ptr<std::ostream> os_factory(bool file){ if (file) return std::make_shared<std::ofstream>("hello.txt"); else return std::make_shared<std::ostringstream>(); a very simple usage scenario: int main(){ auto out = os_factory(false); if (out) (*out) << "hello world\n"; auto fileout = os_factory(true); if (fileout) (*fileout) << "Hello, world!\n"; fileout.reset(); // clears shared_ptr, deallocates stream object not really needed 22
23 Interesting side effects last shared_ptr handle destroyed will delete allocated object if instances of a class hierarchy are always represented by a shared_ptr<base> but created through make_shared<concrete>() the destructor no longer needs to be virtual shared_ptr memorizes concrete destructor for deletion on construction time in make_shared<concrete> shared_ptr can lead to object cycles no longer cleared, because of circular dependency need weak_ptr to break such cycles 23
24 Memory new T{ delete p; NULL (void*)0 < use nullptr Prefer unique_ptr/shared_ptr for heap-allocated objects over T*. Use std::vector and std::string instead of heap-allocated arrays. Peter Sommerlad
25 Example: Parents and Children shared_ptr cycles: weak_ptr/shared_from_this Create a class Person that represents a person Each Person knows about its parents (father/mother) if they are still alive Each Person can be married Each Person knows about its children both mother and father know about their children Observation: can not use direct members, would incur copying persons 25
26 Summary shared & weak ptr Be careful when creating object structures with shared_ptr -> avoid circular object dependencies require deliberate breaking to get rid of the instantiated objects use weak_ptr consequently keep all "living" objects in a separate data structure as shared_ptr and model dependencies through weak_ptr removing from "live list" destroys object Memory released when last weak_ptr expires 26
27 Model (part of) first biblical family Adam Eve sons: Abel, Cain, Seth represent Cain's murder of Abel represent Adams death represent Eve's death show a person with its name, parents' names and children's names 27
28 Steps and Effects Adam 1 Eve Adam 3 Eve Cain Abel Seth Cain Abel Seth Adam 2 Eve Adam 4 Eve Cain Abel Seth Cain Abel Seth 28
29 First cut on shared_ptr #include <memory> #include <string> #include <vector> #include <iosfwd> using PersonPtr=std::shared_ptr<class Person>; class Person { std::string name; std::vector<personptr> children; public: Person(std::string name):name{name{ void addchild(personptr child){ children.push_back(child); void print(std::ostream &) const; static PersonPtr makeperson(std::string name){ ; can define shared_ptr with incomplete type store shared_ptr in vector return std::make_shared<person>(name); #include "Person.h" #include <ostream> void Person::print(std::ostream& out) const { out << "Person: "<< name; out << "\n "; for(auto child:children){ out << child->name << ", "; out << '\n'; 29
30 first main() #include "Person.h" #include <iostream> void addson(std::string name,personptr adam, PersonPtr eva) { auto son = Person::makePerson(name); eva->addchild(son); adam->addchild(son); must add shared_ptr not object! int main() { auto adam=person::makeperson("adam"); adam->print(std::cout); auto eva=person::makeperson("eva"); eva->print(std::cout); addson("cain",adam, eva); addson("abel",adam, eva); addson("seth",adam, eva); adam->print(std::cout); eva->print(std::cout); // how to have Cain kill Abel? Person: Adam Person: Eva Person: Adam Cain, Abel, Seth, Person: Eva Cain, Abel, Seth, 30
31 Adam 2 Eve 2nd cut: "killing Abel" Cain Abel Seth know your parents class Person { std::string name; PersonPtr father; PersonPtr mother; std::vector<personptr> children; public: Person(std::string name, PersonPtr father,personptr mother) :name{name,father{father,mother{mother{ void addchild(personptr child){ children.push_back(child); std::string getname() const { return name; PersonPtr findchild(std::string name) const; void killchild(personptr child); void print(std::ostream &) const; static PersonPtr makeperson(std::string name, PersonPtr father={, PersonPtr mother={){ auto res = std::make_shared<person>(name,father,mother); if (father) father->addchild(res); if (mother) mother->addchild(res); return res; ; search and get rid of children 31
32 Adam 2 Eve 2nd cut: "killing Abel" void Person::print(std::ostream& out) const { out << "Person: "<< name ; out << " "<< (father?father->getname():"orphan"); out << " "<< (mother?mother->getname():"orphan"); out << "\n "; for(auto const &child:children){ out << child->name << ", "; out << '\n'; PersonPtr Person::findChild(std::string thename) const { using namespace std::placeholders; auto finder=[thename](personptr const &person){ return person->getname() == thename; ; auto it=find_if(children.begin(),children.end(),finder); if (it!= children.end()) return *it; return nullptr; void Person::killChild(PersonPtr child) { if (child){ children.erase(find(children.begin(),children.end(),child)); //if (child->father == )? know your parents search children, predicate as lambda nullptr means empty shared_ptr erase found object, shared_ptr == used Cain Abel Seth 32
33 Adam 2 Eve 2nd cut: "killing Abel" main() Cain Abel Seth #include "Person.h" #include <iostream> void addson(std::string name,personptr adam, PersonPtr eva) { auto son = Person::makePerson(name); eva->addchild(son); adam->addchild(son); int main() { auto adam=person::makeperson("adam"); adam->print(std::cout); auto eva=person::makeperson("eva"); eva->print(std::cout); addson("cain",adam, eva); addson("abel",adam, eva); addson("seth",adam, eva); adam->print(std::cout); eva->print(std::cout); // how to have Cain kill Abel? { auto abel=eve->findchild("abel"); eve->killchild(abel); adam->killchild(abel); abel->print(std::cout); eve->print(std::cout); // how can we kill Adam? last shared_ptr after killchild killing means forgetting all references Person: Adam orphan orphan Person: Eve orphan orphan Person: Adam orphan orphan Cain, Abel, Seth, Person: Eve orphan orphan Cain, Abel, Seth, Person: Abel Adam Eve Person: Eve orphan orphan Cain, Seth, 33
34 Problem: can not access shared_ptr class Person : public std::enable_shared_from_this<person> { CRTP solution: inherit from enable_shared_from_this CRTP pattern, pass own class as template argument access through shared_from_this() function can not do that in constructor or destructor! auto me=shared_from_this(); // or PersonPtr me=shared_from_this(); 34
35 Adam 3 Eve 3rd cut: "Adam can die" Cain Abel Seth class Person : public std::enable_shared_from_this<person> { std::string name; PersonPtr father; PersonPtr mother; std::vector<personptr> children; public: Person(std::string name,personptr father,personptr mother) :name{name,father{father,mother{mother{ // can not do shared_from_this here! // if(father) father->addchild(shared_from_this()); void addchild(personptr child){ children.push_back(child); std::string getname() const { return name; PersonPtr findchild(std::string name) const; void killchild(personptr child); void killme(); void print(std::ostream &) const; static PersonPtr makeperson(std::string name, PersonPtr father={, PersonPtr mother={){ auto res = std::make_shared<person>(name,father,mother); if (father) father->addchild(res); if (mother) mother->addchild(res); return res; ; inherit from enable_shared_from_this must still inform parents in factory function! disentangling circular object dependency by hand! void Person::killMe() { auto me=shared_from_this(); if (father) father->killchild(me); if (mother) mother->killchild(me); for(personptr son:children){ if (me == son->father) son->father.reset(); if (me == son->mother) son->mother.reset(); children.clear(); 35
36 Adam 3 Eve 3rd part of main() Cain Abel Seth must disentangle object circular reference before destroying... // how can we kill Adam and Eve? { adam->killme(); adam->print(std::cout); adam.reset(); eve->print(std::cout); auto cain=eve->findchild("cain"); if (cain) cain->print(std::cout); eve->killme(); // avoid memory leak eve->print(std::cout); eve.reset(); last reference to Adam forgotten last reference to Eve forgotten Cain doesn't have children, so no need for killme() Person: Adam orphan orphan Person: Eve orphan orphan Person: Adam orphan orphan Cain, Abel, Seth, Person: Eve orphan orphan Cain, Abel, Seth, Person: Abel Adam Eve Person: Eve orphan orphan Cain, Seth, Person: Adam orphan orphan Person: Eve orphan orphan Cain, Seth, Person: Cain orphan Eve Person: Eve orphan orphan 36
37 Problem: circular object reference using WeakPersonPtr=std::weak_ptr<class Person>; WeakPersonPtr father; // don't lock parent objects WeakPersonPtr mother; solution: make one direction based on weak_ptr internally Observer Pattern recognizes when shared_ptr no longer exists must call lock() to access underlying shared_ptr auto realfather=father.lock(); out <<(realfather?realfather->getname():"orphan"); 37
38 Adam 4 Eve 4th cut: "All can die" Cain Abel Seth PersonPtr Person::myLock() { try { auto me=shared_from_this(); return me; catch(std::bad_weak_ptr const &ex){ std::cout << "++++already dead? " << name<< '\n'; return PersonPtr{; // already dead void Person::killMe() { // here shared_from_this is possible auto me=mylock(); if (!me) return; // already dead auto realfather=father.lock(); if (realfather) realfather->killchild(me); auto realmother=mother.lock(); if (realmother) realmother->killchild(me); children.clear(); throws when called from destructor still need to inform parent, because it keeps a shared_ptr no more need to inform children, because they keep only weak_ptr Person::~Person() { std::cout << "killing me: "<< name << '\n'; //killme(); // can not call shared_from_this() in dtor! just to show what happens, not needed! 38
39 Adam 4 Eve 4th cut: main() int main() { auto adam=person::makeperson("adam"); adam->print(std::cout); auto eve=person::makeperson("eve"); eve->print(std::cout); addson("cain",adam, eve); addson("abel",adam, eve); addson("seth",adam, eve); adam->print(std::cout); eve->print(std::cout); // Cain kills Abel: need to remove from parents { auto abel=eve->findchild("abel"); eve->killchild(abel); adam->killchild(abel); abel->print(std::cout); eve->print(std::cout); // kill Adam by forgetting last reference { std::cout << "killing Adam:\n"; adam->print(std::cout); adam.reset(); eve->print(std::cout); auto cain=eve->findchild("cain"); if (cain) cain->print(std::cout); eve.reset(); if (cain) cain->print(std::cout); no more need to disentangle last reference to Adam forgotten last reference to Eve forgotten Person: Adam orphan orphan Person: Eve orphan orphan Person: Adam orphan orphan Cain, Abel, Seth, Person: Eve orphan orphan Cain, Abel, Seth, Person: Abel Adam Eve killing me: Abel Person: Eve orphan orphan Cain, Seth, killing Adam: Person: Adam orphan orphan Cain, Seth, killing me: Adam Person: Eve orphan orphan Cain, Seth, Person: Cain orphan Eve killing me: Eve killing me: Seth Person: Cain orphan orphan killing me: Cain Cain Abel Seth 39
40 Summary Use it for containers of polymorphic objects with an abstract Base class std::vector<std::shared_ptr<base>> create individual instances of concrete subclasses in a factory function with make_shared<subclass>(...) can pass arguments as with Subclass' constructor Prefer direct members/values instead of heap allocated objects, if possible! 40
COMP6771 Advanced C++ Programming
1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout
More informationC++ Modern and Lucid C++ for Professional Programmers
Informatik C++ Modern and Lucid C++ for Professional Programmers part 13 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015 Inheritance and dynamic Polymorphism base classes,
More informationHomework 4. Any questions?
CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible
More informationPointers. Developed By Ms. K.M.Sanghavi
Pointers Developed By Ms. K.M.Sanghavi Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer Memory Management In order to create
More informationCSE 333 Lecture smart pointers
CSE 333 Lecture 14 -- smart pointers Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New exercise out today, due Wednesday morning Exam Friday
More informationMODERN AND LUCID C++ ADVANCED
Informatik MODERN AND LUCID C++ ADVANCED for Professional Programmers Prof. Peter Sommerlad Thomas Corbat Director of IFS Research Assistant Rapperswil, FS 2016 LIBRARY API/ABI DESIGN PIMPL IDIOM HOURGLASS
More informationPart 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 informationC++ Modern and Lucid C++ for Professional Programmers
Informatik C++ Modern and Lucid C++ for Professional Programmers Part 1 Self-study for Introduction to C++ Prof. Peter Sommerlad Director IFS Institute for Software Rapperswil, HS 2017 Thomas Corbat Additional
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 informationC++ Modern and Lucid C++ for Professional Programmers
Informatik C++ Modern and Lucid C++ for Professional Programmers part 9 Prof. Peter Sommerlad Institutsleiter IFS Institute for Software Rapperswil, HS 2015 Functors and Parameterizing STL Functors, Lambdas,
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Smart Pointers and Constness Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de Summer
More informationDatabase Systems on Modern CPU Architectures
Database Systems on Modern CPU Architectures Introduction to Modern C++ Moritz Sichert Technische Universität München Department of Informatics Chair of Data Science and Engineering Overview Prerequisites:
More informationCSE 333 Lecture smart pointers
CSE 333 Lecture 14 -- smart pointers Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia Midterm Friday - Review in sections this week - Closed book; topic list
More informationModern and Lucid C++ Advanced for Professional Programmers. Part 3 Move Semantics. Department I - C Plus Plus Advanced
Department I - C Plus Plus Advanced Modern and Lucid C++ Advanced for Professional Programmers Part 3 Move Semantics Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 09.03.2018 HS2018 Move Semantics 2
More informationCS 376b Computer Vision
CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves
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 information6 Architecture of C++ programs
6 Architecture of C++ programs 1 Preview managing memory and other resources "resource acquisition is initialization" (RAII) using std::auto_ptr and other smart pointers safe construction of an object
More informationCOMP 2355 Introduction to Systems Programming
COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract
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 informationRAII and Smart Pointers. Ali Malik
RAII and Smart Pointers Ali Malik malikali@stanford.edu Game Plan Recap Conversion Operators RAII Smart Pointers Recap Initialisation: Initialisation vs Assignment Transforms an object s initial junk data
More informationModern and Lucid C++ Advanced for Professional Programmers. Part 1 C Plus Plus Recap. Department I - C Plus Plus
Department I - C Plus Plus Modern and Lucid C++ Advanced for Professional Programmers Part 1 C Plus Plus Recap Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 23.02.2018 HS2018 Values vs. References
More informationElevate your Code to Modern C++ with Automated Tooling. Peter Sommerlad
Elevate your Code to Modern C++ with Automated Tooling Peter Sommerlad Simple C++ Less Code == More Software Know your language and its (modern) idioms Don t be afraid of STL or templates Start small.
More informationCE221 Programming in C++ Part 1 Introduction
CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab
More informationCSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers
CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers Review from Lecture 23 Basic exception mechanisms: try/throw/catch Functions & exceptions, constructors & exceptions Today
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 informationSmart Pointers in C++11
Smart Pointers in C++11 Karl Stratos 1 Background 1.1 Pointers When we write T x to create an instance x of type T, we allocate the amount of memory required for T and names it as x. We can reference (i.e.,
More informationSmart Pointers. Some slides from Internet
Smart Pointers Some slides from Internet 1 Part I: Concept Reference: Using C++11 s Smart Pointers, David Kieras, EECS Department, University of Michigan C++ Primer, Stanley B. Lippman, Jesee Lajoie, Barbara
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 informationC++ Smart Pointers. CSE 333 Autumn 2018
C++ Smart Pointers CSE 333 Autumn 2018 Instructor: Hal Perkins Teaching Assistants: Tarkan Al-Kazily Renshu Gu Trais McGaha Harshita Neti Thai Pham Forrest Timour Soumya Vasisht Yifan Xu Administriia New
More informationC++ Programming Lecture 7 Software Engineering Group
C++ Programming Lecture 7 Software Engineering Group Philipp D. Schubert Contents 1. Template metaprogramming 2. Variadic template arguments 3. Smart pointer Template metaprogramming Template metaprogramming
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 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 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 informationCE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings
CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location
More informationThe issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management
Session 8 Memory Management The issues Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Programs manipulate data, which must be stored
More informationAssertions and Exceptions
CS 247: Software Engineering Principles Assertions and Exceptions Reading: Eckel, Vol. 2 Ch. 1 Exception Handling U Waterloo CS247 (Spring 2017) p.1/32 Defensive Programming The question isn t whether
More informationCSE 303: Concepts and Tools for Software Development
CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010
CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)
More informationC++ Programming Lecture 7 Software Engineering Group
C++ Programming Lecture 7 Software Engineering Group Philipp D. Schubert Contents 1. Template metaprogramming 2. Variadic template arguments 3. Smart pointer Template metaprogramming Template metaprogramming
More informationModernizing legacy C++ code
Modernizing legacy C++ code Marius Bancila mariusbancila marius.bancila Agenda Short intro Legacy and modernization Good practices Q&A Containers Resource management correctness Const correctness Type
More informationCS11 Advanced C++ Spring 2018 Lecture 1
CS11 Advanced C++ Spring 2018 Lecture 1 Welcome to CS11 Advanced C++! A deeper dive into C++ programming language topics Prerequisites: CS11 Intro C++ track is strongly recommended (obvious) You should
More informationCA341 - Comparative Programming Languages
CA341 - Comparative Programming Languages David Sinclair Dynamic Data Structures Generally we do not know how much data a program will have to process. There are 2 ways to handle this: Create a fixed data
More information04-17 Discussion Notes
04-17 Discussion Notes PIC 10B Spring 2018 1 RAII RAII is an acronym for the idiom Resource Acquisition is Initialization. What is meant by resource acquisition is initialization is that a resource should
More informationModern and Lucid C++ Advanced for Professional Programmers. Part 12 Advanced Library Design. Department I - C Plus Plus Advanced
Department I - C Plus Plus Advanced Modern and Lucid C++ Advanced for Professional Programmers Part 12 Advanced Library Design Thomas Corbat / Prof. Peter Sommerlad Rapperswil, 23.02.2017 HS2017 Topics
More informationCSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers
CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers Announcements Please fill out your course evaluations! Those of you interested in becoming an undergraduate mentor for
More informationCSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many
More informationCOMP6771 Advanced C++ Programming
1.... COMP6771 Advanced C++ Programming Week 5 Part One: Exception Handling 2016 www.cse.unsw.edu.au/ cs6771 2.... Memory Management & Exception Handling.1 Part I: Exception Handling Exception objects
More informationA Generic Non-intrusive Smart Pointer Implementation
A Generic Non-intrusive Smart Pointer Implementation Anthony Williams 13th March 2001 1 Background I started writing an article about resource management using Resource Acquisition Is Initialisation (RAII),
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 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 informationC++ is Evolving. std::array
C++ is Evolving C++ is an evolving language. A committee of the ISO (International Organization for Standards) ratifies proposed changes to C++. New standards have been released every few years. In this
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 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 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 informationStructuur van Computerprogramma s 2
Structuur van Computerprogramma s 2 dr. Dirk Deridder Dirk.Deridder@vub.ac.be http://soft.vub.ac.be/ Vrije Universiteit Brussel - Faculty of Science and Bio-Engineering Sciences - Computer Science Department
More informationCommon Misunderstandings from Exam 1 Material
Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself
More informationAdvanced Programming & C++ Language
Advanced Programming & C++ Language ~10~ C++11 new features Ariel University 2018 Dr. Miri (Kopel) Ben-Nissan 2 Evolution of C++ Language What is C++11? 3 C++11 is the ISO C++ standard formally ratified
More informationVector and Free Store (Pointers and Memory Allocation)
DM560 Introduction to Programming in C++ Vector and Free Store (Pointers and Memory Allocation) Marco Chiarandini Department of Mathematics & Computer Science University of Southern Denmark [Based on slides
More informationCute C++ idioms Nikhil Marathe.
Cute C++ idioms Nikhil Marathe http://nikhilism.com Everybody knows 10% of C++ Qt style No exceptions Return values indicate errors Well defined memory models Qt tree based ownership, occasional ref counting
More informationAdvanced C++ 4/13/2017. The user. Types of users. Const correctness. Const declaration. This pointer and const.
The user. Advanced C++ For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 #define private public #define protected public #define class struct Source: Lutz
More informationevelop C++ (CORE) GUIDELINES - SAFER C++ NDC Techtown Guidelines, Tools und Feedback Prof. Peter Sommerlad Director of IFS August 2018
NDC Techtown evelop ++ C++ (CORE) GUIDELINES - SAFER C++ Guidelines, Tools und Feedback Prof. Peter Sommerlad Director of IFS August 2018 Download IDE at: www.cevelop.com My Goal: Eliminate Bad Software!
More informationECE 449 OOP and Computer Simulation Lecture 12 Resource Management II
ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/62 ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II Professor Jia Wang Department of Electrical
More informationC++ Programming Lecture 4 Software Engineering Group
C++ Programming Lecture 4 Software Engineering Group Philipp D. Schubert VKrit Date: 24.11.2017 Time: 15:45 h Your opinion is important! Please use the free text comments Contents 1. Operator overloading
More informationCSE 333 Lecture smart pointers
CSE 333 Lecture 13 -- smart pointers Steve Gribble Department of Computer Science & Engineering University of Washington Administrivia HW2 is due on Thursday! - check out the discussion board for a few
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 informationChapter 2. Procedural Programming
Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic
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 informationPointers! Arizona State University 1
Pointers! CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 10 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More information377 Student Guide to C++
377 Student Guide to C++ c Mark Corner January 21, 2004 1 Introduction In this course you will be using the C++ language to complete several programming assignments. Up to this point we have only provided
More informationIntermediate C++ 1/83
Intermediate C++ 1/83 Sections I. Memory Management Basics II. The C++ Standard Library III. Casting IV. Resource Management: RAII 2/83 I. Memory Management Basics 1. Checking for memory leaks 2. Pass
More informationEvolution of Programming Languages
Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,
More informationMaking New Pseudo-Languages with C++
Making New Pseudo-Languages with C++ Build You a C++ For Great Good ++ A 10,000 Metre Talk by David Williams-King Agenda 1/4 Introduction 2/4 Polymorphism & Multimethods 3/4 Changing the Behaviour of C++
More informationAdvanced Systems Programming
Advanced Systems Programming Introduction to C++ Martin Küttler September 19, 2017 1 / 18 About this presentation This presentation is not about learning programming or every C++ feature. It is a short
More informationCMSC 330: Organization of Programming Languages. Ownership, References, and Lifetimes in Rust
CMSC 330: Organization of Programming Languages Ownership, References, and Lifetimes in Rust CMSC330 Spring 2018 1 Memory: the Stack and the Heap The stack constant-time, automatic (de)allocation Data
More informationUsing C++11 s Smart Pointers
Using C++11 s Smart Pointers David Kieras, EECS Department, University of Michigan May 2015 This tutorial deals with C++11's smart pointer facility, which consists unique_ptr, shared_ptr and its partner,
More information18. Dynamic Data Structures I. Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors
590 18. Dynamic Data Structures I Dynamic Memory, Addresses and Pointers, Const-Pointer Arrays, Array-based Vectors Recap: vector 591 Can be initialised with arbitrary size n 591 Recap: vector
More informationChapter 17 vector and Free Store
Chapter 17 vector and Free Store Bjarne Stroustrup www.stroustrup.com/programming Overview Vector revisited How are they implemented? Pointers and free store Allocation (new) Access Arrays and subscripting:
More informationC++ Important Questions with Answers
1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children
More informationWhere do we go from here?
Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons
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 informationException Safe Coding
Exception Safe Coding Dirk Hutter hutter@compeng.uni-frankfurt.de Prof. Dr. Volker Lindenstruth FIAS Frankfurt Institute for Advanced Studies Goethe-Universität Frankfurt am Main, Germany http://compeng.uni-frankfurt.de
More informationC++ Primer. CS 148 Autumn
C++ Primer CS 148 Autumn 2018-2019 1 Who is this for? If you are taking this class and are not familiar with some of the features of C++, then this guide is for you. In other words, if any of these words
More informationConsider the program...
Smart Pointers Consider the program... When the scope of foo is entered storage for pointer x is created The new allocates storage on the heap class X {... When the scope foo is left, the storage for x
More informationEngineering Robust Server Software
Engineering Robust Server Software Exceptions Exceptions Handling problems: exceptions C++ Java temp-and-swap RAII Smart Pointers finally specifications finalizers (and why they are not what you need for
More informationCSE 333 Final Exam December 13, 2017 Sample Solution
Question 1. (16 points) STL. Implement the template function is_sorted, below, so it returns true if its list argument is sorted in non-decreasing order, and returns false if not. Your function should
More informationA Tour of the C++ Programming Language
A Tour of the C++ Programming Language We already know C Everything that can be done with a computer, can be done in C Why should we learn another language? Newer languages provide a bigger toolbox Some
More informationCSCI-1200 Data Structures Spring 2018 Lecture 25 Garbage Collection & Smart Pointers
CSCI-1200 Data Structures Spring 2018 Lecture 25 Garbage Collection & Smart Pointers Announcements Please fill out your course evaluations! Those of you interested in becoming an undergraduate mentor for
More informationECE 449 OOP and Computer Simulation Lecture 14 Final Exam Review
ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/35 ECE 449 OOP and Computer Simulation Lecture 14 Final Exam Review Professor Jia Wang Department of Electrical
More informationCSE 333 Lecture 9 - intro to C++
CSE 333 Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington Administrivia & Agenda Main topic: Intro to C++ But first: Some hints on HW2 Labs: The
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 informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationChapter 17 vector and Free Store
Chapter 17 vector and Free Store Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~hkaiser/fall_2010/csc1253.html Slides adapted from: Bjarne Stroustrup, Programming Principles and Practice using
More informationChapter 13: Copy Control. Overview. Overview. Overview
Chapter 13: Copy Control Overview The Copy Constructor The Assignment Operator The Destructor A Message-Handling Example Managing Pointer Members Each type, whether a built-in or class type, defines the
More informationThe University of Nottingham
The University of Nottingham SCHOOL OF COMPUTER SCIENCE A LEVEL 2 MODULE, SPRING SEMESTER 2011-2012 G52CPP C++ Programming Examination Time allowed TWO hours Candidates may complete the front cover of
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 informationMajor Differences between Java and C++ Programming in C++ Multiple Inheritance
Programming in C++ Session 7 - Multiple Inheritance Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Major Differences between Java
More informationBypassing Memory Leak in Modern C++ Realm
Annales Mathematicae et Informaticae 48 (2018) pp. 43 50 http://ami.uni-eszterhazy.hu Bypassing Memory Leak in Modern C++ Realm Dorottya Papp, Norbert Pataki Dept. of Programming Languages and Compilers,
More informationEL2310 Scientific Programming
Lecture 14: Object Oriented Programming in C++ (fpokorny@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes
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 informationSmart Pointers - What, Why, Which?
Page 1 of 7 Smart Pointers - What, Why, Which? Yonat Sharon What are they? Why would I use them? Less bugs Exception Safety Garbage collection Efficiency STL containers Which one should I use? Local variables
More information