[PDF] CS11 Advanced C++ Welcome to CS11 Advanced C++!. •





Previous PDF Next PDF



A Complete Guide to Programming in C++

This book was written for readers interested in learning the C++ programming language from scratch and for both novice and advanced C++ programmers wishing to 



Advanced C++ Topics Advanced C++ Topics

Generic programming via templates. Page 4. CONSTRUCTION AND DESTRUCTION. Constructors: Special Member Functions for object initialization. – Same name as the 



Modern C++ Object-Oriented Programming CPP Modern C++ Object-Oriented Programming CPP

C++ - Object-Oriented Programming. Course content. − Introduction to C++ − Advanced Class Features. − Operator overloading. − Object Relationships.



Advanced C++ A P I User Guide

Purpose. The Advanced C++ A P I User Guide describes the way to use the C++ programming This manual the Advanced C++ A P I User Guide



CS 144 Advanced C++ Programming

CS 144 Advanced C++ Programming The university's syllabus policies: • University Syllabus Policy S16-9 at ​http://www.sjsu.edu/senate/docs/S16-9.pdf.



COMP6771 Advanced C++ Programming - 2emWeek 9 Multithreading COMP6771 Advanced C++ Programming - 2emWeek 9 Multithreading

Advanced C++ Programming. Week 9. Multithreading. 2016 www.cse.unsw.edu.au/˜cs6771. 1. Page 2 . . . . . Overview . . . . . . . . . . . . Shared Memory.



Object Oriented Programming Using C++

We use dynamic allocation techniques when it is not known in advance how much of memory space as needed . C++ also support those functions it also defines two 



CS 144 Advanced C++ Programming

CS 144 Advanced C++ Programming The university's syllabus policies: • University Syllabus Policy S16-9 at ​http://www.sjsu.edu/senate/docs/S16-9.pdf.



C++ Programming for Scientists

Thus in one situation the class data and member functions could be working on integers and in another on a more advanced data type. But again



Object-Oriented Programming in C++ Fourth Edition

This book teaches object-oriented programming with the C++ programming In books on C programming structures are often considered an advanced feature and are ...



A Complete Guide to Programming in C++

This book was written for readers interested in learning the C++ programming language from scratch and for both novice and advanced C++ programmers.



Advanced C++ Topics

Advanced C++ Topics C++ vs C. Some more keywords. – new delete



Modern C++ Object-Oriented Programming CPP

move(66);. // } Page 90. OOP: Advanced class features. Array of objects.



OReilly - Practical C++ Programming.pdf

Programming Exercises. 245. Answers to Chapter Questions. 245. Page x. IV: Advanced Programming Concepts. 249. 16: File Input/Output. 251. C++ File I/O.



Modern C++ Tutorial: C++11/14/17/20 On the Fly

18. 9. 2022. The content in this PDF file may outdated please check our website or GitHub repository for the latest book updates. License. This work was ...



CS11 Advanced C++

Welcome to CS11 Advanced C++!. • A deeper dive into C++ programming language topics Implementing C++ classes and functions / member-functions.



The C++ Language Tutorial

Pointers are a very powerful feature of the C++ language that has many uses in advanced programming. Farther ahead we will see how this type of variable is 



S7-PLCSIM Advanced

SIMATIC CPUs and CPU programming. ? PC-based automation using S7-1500 and WinCC Runtime Advanced. ? Development of software in C++ and C#.



Advanced C++ Template Techniques: An Introduction to Meta

Advanced C++ Template Techniques: C++ templates were originally designed to reduce ... so how useful is template meta-programming in real life ?



Advanced Linux Programming

31. 7. 2000. Throughout this book we'll assume that you're familiar with the C or C++ programming languages and the most common functions in the ...

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 be familiar with:•Implementing C++ classes and functions / member-functions•Basic use of the C++ standard library -strings, collection templates, stream IO and stream-based file IO•Pointers and references (not necessarily rvalue-references)•Basic operator overloading•Proper use of constkeyword•Basic exception handling•Using tools like make and Doxygen

Assignments and Grading•Each lecture has a corresponding lab for 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 must be addressed)•0 = incorrect (worthy of no credit)•Must receive at least 75% of all possible points to pass track•Can submit up to 2 reworks of labs 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

Assignments and Grading (2)•All code submitted is expected to be well documented and written in a clean, uniform coding style•Specifics of coding style are not as relevant to me•Consistency is the most important thing•Use Doxygento generate docs from C++ code•doxygen-gto generate initial Doxyfileconfig-file•Edit configuration file to generate HTML docs only, into a subdirectory•doxygenshould generate docs after that•See http://www.stack.nl/~dimitri/doxygen/for more details•Initially will use makefor building projects

C++ Compiler•Can use g++/gdbor clang++/lldbfor 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/17 for your implementations•Can ask the compiler what version of C++ is its default•g++ -dM-E -x c++/dev/null | grep cplusplus#define __cplusplus201402L•clang++ -dM-E -x c++/dev/null | grep cplusplus#define __cplusplus199711L•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

Local Variables and Destructors•Normally, destructors are called when variables go out of scopevoid myFunction() {Class1 var1;Class2 var2{"out.txt"};var1.doStuff(var2);}•Compiler automatically inserts destructor calls in the appropriate places•Your code doesn't manually call destructors, ever.var2.~Class2();var1.~Class1();Compiler adds:

Destructors and ExceptionsvoidmyFunction() {Class1 var1;Class2 var2{"out.txt"};var1.doStuff(var2);}•What happens if var2constructor throws?•Only var1was constructed, so only var1destructor gets calledvar2.~Class2();var1.~Class1();THROW!propagateexceptioncleanup(stack unwinding)

Destructors and Exceptions (2)voidmyFunction() {Class1 var1;Class2 var2("out.txt");var1.doStuff(var2);}•What happens if var1constructor throws?•Nothing was constructed, so no destructors get calledvar2.~Class2();var1.~Class1();propagateexceptionno cleanupneededTHROW!

Destructors and Exceptions (3)voidmyFunction() {Class1 var1;Class2 var2("out.txt");var1.doStuff(var2);}•What happens if var1.doStuff(var2)throws?•Both var1and var2were constructed, so both destructors get called (in reverse order of construction)var2.~Class2();var1.~Class1();THROW!propagateexceptioncleanup(stack unwinding)

Classes and Exceptions•Similar model used when constructors throwclass Logger {LogConfigconfig;RotatingFileoutputFile;public:Logger(conststring &configFile) {... // initialize logger}...};•What happens if the constructor body throws?•The new Loggerinstance failed to be constructed•configand outputFilehave already been initialized, so their destructors are automatically calledTHROW!

Classes and Exceptions (2)•Member initialization might also throwclass Logger {LogConfigconfig;RotatingFileoutputFile;public:Logger(conststring &configFile) :config{configFile}, outputFile{config} {... // initialize logger}...};•What happens if outputFileconstructor throws?•The new Loggerinstance failed to be constructed (again)•configwas already initialized, so its destructor gets calledTHROW!

Classes and Exceptions (3)•Another member constructor throwsclass Logger {LogConfigconfig;RotatingFileoutputFile;public:Logger(conststring &configFile) :config{configFile}, outputFile{config} {... // initialize logger}...};•What happens if configconstructor throws?•The new Loggerinstance failed to be constructed (yet again)•Nothing was initialized, so no member destructors are calledTHROW!

Heap-Allocation and Exceptions•What if members are heap-allocated?Simulator::Simulator(SimConfig*conf) {// Initialize my simulator members.entityData= new Entity[conf->maxEntities];playerData= new Player[conf->maxPlayers];}•If an allocation fails, newwill throw bad_alloc•What happens if second allocation throws bad_alloc?•Simple: entityDatadoesn't get cleaned up

A Safer Constructor•Can fix the problem by doing this:Simulator::Simulator(SimConfig*conf) :entityData{nullptr}, playerData{nullptr} {try {entityData= new Entity[conf->maxEntities];playerData= new Player[conf->maxPlayers];}catch (bad_alloc&ba) {delete[] entityData;delete[] playerData;throw; // Don't forget to propagate this!}}•Not the prettiest code, but at least it's safe.

Again and Again!•This pattern gets old fast:void initSimulation() {SimConfig*conf= new SimConfig{"sim.conf"};Simulator *sim = new Simulator{conf};...}•What if Simulatorconstructor throws?•(sigh)•This approach to leak-free, exception-safe code is a giant pain!

Safe Resource Management•Problem:•Dynamic allocation of resources, plus exception-handling, is a potentially dangerous mix!•Memory allocated with new•Opening files, pipes, etc.•Threads, mutexes, condition variables, semaphores, ...•Just catching exceptions isn't enough!•Also need to release any resources that were allocated before the exception was thrown.

Typical Resource Allocation Model•General form of the problem:void doStuff() {// acquire resource 1// ...// acquire resource N// use the resources// release resource N// ...// release resource 1}•Resources usually released in opposite order of allocation•Hey, C++ constructors and destructors do this!•Local variables are created and destroyed this way

Simpler Leak-Proofing Approach•Make a wrapper class for managing a dynamic resource•Constructor allocates the dynamic resource, orconstructor assumes ownership of the resource•Destructor frees the resource•Use the wrapper class for local variables•i.e. don'tdo "new Wrapper(resource)" !!!•"Clean up" handlers become unnecessary•When exception is thrown, C++ calls wrapper-class destructor automatically, since it's local.

Resource Acquisition Is Initialization•Pattern called: Resource Acquisition Is Initialization (RAII for short)•A local variable's constructor immediately assumes ownership of the dynamic resource•C++ will call the destructor at the Right Time.•Typically realized as "smart pointers"•They follow this model for heap-allocated memory•This can be applied to anydynamic resource•Files! Semaphores! Mutexes! ...

C++ Smart Pointers•C++11 Standard Library introduced two smart-pointer classes (originally part of Boost library)•std::shared_ptris a multiple-ownershipsmart pointer for when dynamically-allocated memory is shared by multiple parts of a program•Manages a T*, allocated with "new T(...)"•std::unique_ptris a single-ownershipsmart pointer for when dynamically-allocated memory is used by only one part of a program•Also manages a T*, allocated with "new T(...)"•#include to use these smart-pointers

C++ Smart Pointers (2)•shared_ptruses reference-counting to track how many parts of the program are using an object•Reference-counting imposes a (slight) time and space overhead•unique_ptrassumes it is sole owner of the memory•No reference-counting overhead•Only one unique_ptrmay point to a given T*•Use unique_ptrwhen only one part of your program needs to access/manage a heap-allocated chunk of memory•e.g. local variable within a function, or owned by a single object•Use shared_ptrwhen several parts of your program need to access/manage a heap-allocated chunk of memory•e.g. if multiple objects need to manage a single chunk of memory•(e.g. if you were implementing a tree or graph data structure)

Smart Pointer Operator Overloads•Smart pointer classes overload these operators:•Dereference (member-access) operator ->•Dereference operator *(not multiplication...)•Allows the smart-pointer to act like a pointer•Smart pointers don't support other common pointer operations, e.g. pointer-arithmetic•For example: no ++and --operator overloads!•Cannot use =to assign raw pointer to smart pointer•Forces thoughtful consideration of how objects are managed•e.g. reset(T*)to assign a raw pointer to a smart pointer, or reset()to set a smart pointer to nullptr•Can assign a smart pointer value to another smart pointer

Usage Examples•Example:#include shared_ptr spw{new Widget{}};unique_ptr upw{new Widget{}};•Can create an alias for the shared-pointer type:using sp_widget_t= shared_ptr;using up_widget_t= unique_ptr;sp_widget_tspw{new Widget{}};up_widget_tupw{new Widget{}};

Usage Examples (2)•C++ also provides two helper functions to wrap initialization#include sp_widget_tspw= make_shared{};up_widget_tupw= make_unique{}•These are actually variadic function templates that call the specified class' constructor•Can pass arguments to the class' constructor as well

Usage Examples (3)•Example:class Widget {...public:Widget();Widget(conststring &type, float weight);...};spw1 = make_shared{};spw2 = make_shared{"frob", 4.3};•Heap-allocates two Widgetobjects, and manages them with smart pointers•Second Widgetinitialized with two-argconstructor

Smart Pointers and Destructors•With proper use of smart pointers and make_shared/make_unique, should never need to directly use newor deletein your code•Destructors also become unnecessary (!!!)•If class wraps all allocations with smart-pointer members, they will automatically delete allocations at the right time•This affects the Rule of Three / Rule of Five•If your class defines any of the following:•A destructor, a copy-constructor, a copy-assignment operator•[Rule of Five: A move-constructor, a move-assignment operator]•It probably needs to define all three [all five].•Destructor will become unnecessary, but other important member functions are likely still essential

Smart Pointers and Destructors (2)•Can either leave out the destructor (the compiler will generate a default for you)•Or, can specify you are using the default destructorclass MyClass{MyClass() { ... }~MyClass() = default;...};•Second option will explicitly document that your class doesn't require a custom destructor

This Week's Assignment•This week:•Build a TreeSet, an ordered set implementation, to store intvalues•Use a binary search tree for internal representation•Each node stores a value V•A node's left subtree holds values less than V•A node's right subtree holds values greater than V•Tree does notneed to be kept balanced•Encapsulate all implementation details!•Class should not expose that it uses a tree internally•Use smart pointers everywhere in implementation

This Week's Assignment (2)•When writing data structures in C++, must frequently decide between using smart pointers and raw pointers•For particularly complicated structures (e.g. graphs), raw pointers may in fact be better than smart pointers•Smart pointers can't deal with cycles in reference graph due to using reference-counting internally•Updating reference-counts in shared pointers is a cost that will add up over time•A binary search tree is simple enough to use shared pointers without increasing complexity too much•A good opportunity to practice using smart pointers J•Moral: Always pick the best tool for the job!

quotesdbs_dbs14.pdfusesText_20
[PDF] advanced calculator app for android

[PDF] advanced cisco router configuration pdf

[PDF] advanced complex analysis pdf

[PDF] advanced computational methods in science and engineering pdf

[PDF] advanced concepts in java

[PDF] advanced css book

[PDF] advanced css3 tutorial pdf free download

[PDF] advanced dance moves ballet

[PDF] advanced db2 sql queries

[PDF] advanced dos commands pdf

[PDF] advanced english class pdf

[PDF] advanced english expressions list

[PDF] advanced english grammar test pdf

[PDF] advanced english learning book pdf

[PDF] advanced english lesson plans pdf