Static initializers in C++

Size: px
Start display at page:

Download "Static initializers in C++"

Transcription

1 Static initializers in C++ Umesh Nair June Introduction The problem of wrong order of static initialization causes applications to crash. People try several workarounds-changing the order of dynamic libraries, tweaking the linker behavior etc. With the need to support multiple platforms and different environments, this problem needs to be solved in a more robust way. In this document 1, various feasible solutions to avoid static initializer ordering problem are discussed. 2 The Problem Consider the following class declaration: class A { public: void foo() {... ; Consider the following definition of a global object in a translation unit T1: A global_a; Consider the following declaration of class B: extern A global_a; class B { public: 1 Extracted from an internal presentation done in Mentor Graphics Corporation. 1

2 ; B() {... global_a.foo(); An object of B is constructed based on the current state of the global object global_a. This will work fine if all objects of B are allocated on the stack or the heap. The object global_a, like all global objects, is constructed before main(), and will be available when the B object is constructed. But the situation is different if there is a global object of type B defined in a translation unit different than T1. 2 So, if a definition B global_b; appears in a translation unit T2, C++ standard doesn t guarantee that global_a will be initialized before global_b. This will cause the construction of global_b giving undesired effects. 3 Techniques to avoid static initializer ordering problem Several articles have been written on this subject in various newsgroups, books and journals. Many of the suggestions may not be implemented in certain codebase, because of one of the following reasons: 1. The compilers may not support these techniques. 2. Shared library compatibility issue. 3. Issues in a major redesign. 4. Issues in forcing modifications in client. applications The following are some feasible solutions. 3.1 Avoid global variables of non-primitive datatypes If possible, this is the best solution. This may not be possible because of the constraints (2) and (3). However, there are situations, where a global variable may be replaced by a local variable or a class variable. 2 If they are in the same translation unit, C++ standard guarantees that global objects will be initialized in the order they are defined. 2

3 3.2 Use a lazy allocation technique In lazy allocation techniques, we convert a global object to a non-global object, so that its construction is deferred till the first use. This generally provides an adequate solution, but has the following disadvantages: 1. They are not thread-safe, because there is no global object. 2. They may impact performance, because an extra function call overhead is there, and in many cases, a global object is replaced by a heap object. 3. This will have a problem if there are destruction order dependencies also, because these techniques do not control the order in which the objects are destroyed. Some lazy allocation techniques are considered below: Replace the global variable with a global pointer that will be dynamically allocated when it is needed Instead of defining the global variable by A global_a; define a function A& get_global_a() { static A* p = new A; return *p; The object is allocated on the heap the first time the function get_global_a() is called. Then onwards, the already allocated object is reused. An advantage of this technique is that, it can be implemented without making much code changes. The only modifications are to replace with A global_a; A& get_global_a() { static A* p = new A; return *p; #define global_a (get_global_a()) 3

4 and all the declarations in the form (this may include client code as well) with extern A global_a; A& get_global_a(); #define global_a (get_global_a()) If the extern declaration is in a header file only, only that header file needs to be modified, and the client code need not be modified. Advantages: 1. Easy to implement. Needs minimum code changes, with possibly no client code change at all. However, clients should rebuild. Disadvantages: 1. Breaks the shared library compatibility, hence cannot be implemented in a general library within an environment release cycle. 2. The client programs need to be rebuilt, not just reimporting the libraries. 3. The client code also may have to change, if they have declared the global object as extern, rather than #including a header file. 4. Introduces a memory leak by allocating an object and never deleting it. This can lead to the following problems: (a) Certain resources may not be reclaimed or certain cleanups may not be done. When defining an object with this technique, care should be taken that the destructor of the class does not release any resources the operating system cannot release. (b) Output from tools like Purify will be more messy if one memory leak is introduced per global variable Modification of the previous technique, with a workaround to avoid memory leaks In the last section, we found a technique whose major drawback is the memory leak. It can be worked around by providing the client a way to delete global pointer. Instead of the technique described in the last section, the declaration 4

5 extern A global_a; can be replaced with class For_global_a { private: static A* p; For_global_a(); ~For_global_a(); public: static A& get() { if (0 == p) { p = new A; return *p; static void cleanup() { if (0!= p) { delete p; p = 0; ; #define global_a (For_global_a::get()) and the definition A global_a; can be replaced with A* For_global_a::p = 0; so that whoever using this technique can call For_global_a::cleanup(); as the last statement in their main() function. Advantages: 1. All advantages of the previous technique. 2. Can workaround with memory leak. 5

6 Disadvantages: 1. Not useful when used inside libraries. Need to identify where the cleanup() should be called. 2. The class declaration should be duplicated wherever an extern A global_a is there. If it is only in a header file, this is fine Use a local static object (Meyers Singleton) This is essentially the same method discussed above, except that a local static object is used instead of local static pointer holding a dynamically allocated object. Instead of the definition A& get_global_a() { static A* p = new A; return *p; #define global_a (get_global_a()) in section (1), we can use A& get_global_a() { static A a; return a; #define global_a (get_global_a()) 3.3 Force the global objects into the same compilation unit C++ standard guarantees that global/static objects in the same compilation unit are constructed in the same order as they are defined. This fact can be used in order to make sure that a global object is initialized before one of its dependent is initialized Use a static member of many static variables In the header file where extern A global_a; 6

7 is declared, replace it with static class Global_a_wrapper { private: static A* ap; public: A() { if (0 == ap) { ap = new A; ~A() { if (0!= ap) { delete ap; ap = 0; // The following two operators are overloaded to // provide a proxy-interface to the actual object A* operator-> () { return ap; A& operator* () { return *ap; global_a; and replace the definition with A global_a; A* Global_a_wrapper::ap = 0; The trick here is, there will be a static object global_a of type Global_a_wrapper in each compilation unit, and all these object share the same real object of type A. Since the header file is #included before the definition of any global object in a translation unit, the static object global_a will be constructed before any of them, thus forcing ap to be allocated before them. Advantages: 7

8 1. No memory leaks, because the static objects will be deleted before the program terminates. 2. The resulting global_a object preserves all semantics of the original object, so that the client code need not be changed. 3. If there is a problem in the order (For example, two header files having these definitions may be #included in a source file, and a wrong order of definitions happens), it will be caught during compilation, and it can be rectified easily. Disadvantages: 1. If the original global object is declared in the client code as an extern, this mechanism need to be put there, or it should #include the appropriate header file. This forces changing the client code. 2. It breaks the shared library compatibility. 3. Should be careful when we have too many of these objects. The program may fail to compile if header files are #included in the wrong order. So, it is better to include header files having these definitions inside header files rather than source files. This may create a maintenance complexity The Nifty Counter approach The technique discussed in the previous section deletes global object ap when the first static object global_a is destroyed. The destruction can be deferred till the last global_a is destroyed. This can be done by using a counter instead of the value of the pointer ap, as follows: static class Global_a_wrapper { private: static A* ap; static size_t counter; public: A() { if (0 == counter++) { ap = new A; ~A() { if (0 == --counter) { delete ap; 8

9 // The following two operators are overloaded to // provide a proxy-interface to the actual object A* operator-> () { return ap; A& operator* () { return *ap; global_a; // In the implementation file size_t Flobal_a_wrapper::counter = 0; A* Global_a_wrapper::ap = 0; To implement the Nifty-counter approach, there is another way taking advantage of the placement new operator : { extern A global_a;... static class Global_a_helper { Global_a_helper() { if (0 == counter++) { new (&global_a) A(some_parameter); ~Global_a_helper() { if (0 == --counter) { // global_a.cleanup(); global_a.~a(); global_a_helper; This is messy. Since the construction need to take place twice, the default constructor should not do anything. If anything needs to be initialized, that should be through a non-default constructor called from the constructor of Global_a_helper constructor. Similarly, the destructor of A also will be called twice, so it also should not do anything. (A cleanup function may be called from ~Global_a_helper() to cleanup.). If A belongs elsewhere, this cannot be 9

10 controlled, and another wrapper class may be needed. This can be implemented in libraries where a global object must be provided for a class it provides. (An example is the std::cout object in the standard iostream library.) 3.4 Solve the problem in the client application, rather than the library There are two techniques to do this Avoid accessing a global object from a constructor If no global object is used in a constructor or functions called by a constructor, there won t be any problem. A possible way to handle it to separate the code to access the global object in a separate function and call that in every member function. For example, consider the code: extern A global_a; class B { private: public: B() { // Some stuff global_a.foo(); ; Replace it with: class B { private: bool flag ; public: B() { // Some stuff flag = false; void init() { extern A global_a; global_a.foo(); flag = true; ; 10

11 and include the following statement in the beginning of every member function of B: if (!flag) { init(); This way, the first member function called will make sure that the initializations needed for B. Advantages: 1. The semantics of the class B remain the same. Doesn t break the shared library compatibility. Disadvantages: 1. This solution requires a fix in the client code (class B) rather than in the library (fix in class A or the global object global_a). Practically, it may be difficult to enforce this. 2. global_a.foo() will not be called until a member function of B is called. This may not be desirable. For example, if this function is called with a parameter specific to the object that calls it, and the order need to be preserved. 3. Care should be taken that init() is not called directly or indirectly from the constructor. So, the member functions called by the constructor should not call init(). Things get complicated if a public member function is called from the constructor. 4. Calling init() in every member function is messy Use a lazy-allocation singleton technique to defer the construction of the client object The lazy allocation technique discussed above can be used for a global variable in the client code also. So, global variables whose class has a constructor referring to another global variable (or, for an ad-hoc solution, global variables that cause problems) can be made singletons, thereby making sure that the global object it refer to is constructed before it is constructed. 11

12 4 Recommended solutions 4.1 Solutions that does not break the shared library compatibility The Shared library compatibility requirement stipulates that no symbols used by any of its client applications should be removed or modified (i.e., the type or semantics is changed) from a shared library, causing an earlier version of an application fail to function, until we declare that our applications will not be compatible with earlier tools and cannot be installed along with those. Generally, such a declaration is done at the beginning of environment releases. Unfortunately, I haven t found any way to solve the static initialization problem in a common library because every solution, except the Nifty counter ( 3.3.2) technique, involves removing a global variable, while the nifty-counter technique is unsuitable for existing libraries. However, solutions can be implemented in the client projects, using a singleton model ( 3.2. Typically, a global variable global_b of class B, which accesses the global variable global_a of class A, can be rewritten as B& get_global_b() { static B b; return b; and the function get_global_b() can be used wherever the global variable global_b was used. Since the variable is constructed at the first invocation of the function, it is guaranteed that the global variable global_a has been constructed by then. However, if this client project is a base library for other projects and requires the shared library compatibility requirement to be satisfied, this fix cannot be implemented there also. Here the only solution is to move the access of the global variable from the constructor to another method. See 3.1 for details. In short, this is done by replacing B() { // Some stuff global a.foo(); with B() { 12

13 // Some stuff flag = false; void init() { extern A global a; global a.foo(); flag = true; where flag is a member variable of type bool, and calling the init() function from every member function as follows: if (!flag) init(); This can be used as an ad-hoc solution. However, as a permanent solution, the Meyers singleton technique described in the next section should be implemented in the next environment release. Here is a suggestion to implement this: 1. Each group should inspect the code in the executables (and not in the shared libraries), and replace the global variables with Meyers singletons. 2. Each group should identify the global objects in the shared libraries, and implement the Meyers singleton technique to them in a conditionally compiled code segment. This should be tested to make sure it will work, but should be disabled when doing an official build, to preserve shared library compatibility. 3. In the next environment release, the #if macros should be reversed or, preferably, the old code should be completely removed, so that all static initialization problems are solved. It should be properly documented, and all downstream clients, if any, should be notified. Cookbooks should be provided for the downstream clients to migrate. 4.2 Permanent solution that may break shared library compatibility constraint For new code, as well as code in an environment release, Meyer s singleton method appears to be the most appropriate method. It is essentially replacing a global variable global_a of type A with the following function: A& get_global_a() { static A a; 13

14 return a; There are two problems with this technique. They are: 1. It is not thread safe, and cannot be used in a multi-threaded environment. 2. If we require the destructors to be called in the exact opposite order of the constructors, this technique cannot be used. 5 Further issues - Thread safety, order of destruction Some techniques have been gave some suggestions to overcome these two problems. They are discussed below: 5.1 Making Meyers singleton technique thread-safe John Hershberger suggested the use of a mutex to force other threads to block while one thread is constructing the static object. Taking the pthreads library as an example, it can be implemented as follows: A& get_global_a_1() { static A* p = 0; // For efficiency. We don t want expensive // mutex calls after initialization if (0 == p) { static pthread_mutex_t si_mutex = WHATEVER_MUTEX; pthread_mutex_lock(&si_mutex); // Need to check again, // p might have been changed by another thread if (0 == p) { static A a; p = &a; pthread_mutex_unlock(&si_mutex); return *p; This will assure that this object will be constructed only once by only one thread. 14

15 5.2 Forcing the destruction order of objects to be the opposite of construction order Don Wakefield suggested a Global Object Manager, which keeps an ordered list of the global objects and its cleanup functions. Global objects can register at the Global Object Manager after they are constructed. The Global Object Manager should be a static object (which should be constructed before any of the global objects), which when destroyed will call the cleanup functions of the global objects in the reverse order. Don and John also suggested that all global objects can be implemented as singleton classes that are inherited from a common base class and having a virtual cleanup() function. Combining these ideas, the following implementation can provide thread-safety as well as right destructor ordering. 1. Define a base class for wrapper singleton classes representing the global objects: class Global_base { public: virtual void cleanup() { delete this; ; Default behavior is to delete the object. However, a child class can provide a different cleanup() function. 2. Implement a Global Object Manager // Function for the for_each algorithm void do_cleanup(global_base* p) { p->cleanup(); class Global_object_manager { typedef vector< Global_base* > vec; private: // Data vec v; private: // Methods // Makes sure that there is only one manager static Global_object_manager& get_manager() { 15

16 static Global_object_manager gm; return gm; // Updates the list with the object information void update(global_base* p) { v.push_back(p); // Constructor should be private. Only one object (created // through get_manager()) should exist Global_object_manager() : v() { public: // Methods // Destructor should be public // Should destroy the objects in the reverse order ~Global_object_manager() { for_each(v.rbegin(), v.rend(), do_cleanup); ; // This is the only function called by other objects // Registers a global object with the manager static void submit(global_base* p) { get_manager().update(p); This will take care of the destructor-order problem. 3. Now the tricky part is to define a wrapper object for every global object. Here is a possible implementation: class Wrapper_global_a : public Global_base { private: A* ap; static Wrapper_global_a* wap; public: static Wrapper_global_a* allocate() { if (0 == wap) { wap = new Wrapper_global_a; return wap; 16

17 A* value() { return ap; private: // Constructor to be called by allocate(). Should be private Wrapper_global_a() { ap = new A; ; // Deleting the object should delete ap ~Wrapper_global_a() { delete ap; // In the implementaion file Wrapper_global_a* Wrapper_global_a::wap = 0; This provides a singleton class that provides a wrapper for the global object. allocate() gives the address of a valid static object, which is constructed only once. value() returns the actual object. The cleanup() function will delete the object in the end. 4. Finally, the function giving the object: A& get_global_a_2() { static A* p = 0; if (0 == p) { static pthread_mutex_t si_mutex = WHATEVER_MUTEX; pthread_mutex_lock(&si_mutex); if (0 == p) { Wrapper_global_a* wp = Wrapper_global_a::allocate(); Global_object_manager::submit(wp); p = wp->value(); pthread_mutex_unlock(&si_mutex); return *p; The first time this function is called, a lock is set, the global object is allocated and registered with the Global Object Manager. Then onwards, 17

18 the allocated object is returned without the overhead of setting a mutex. The Global Object Manager will destroy the wrapper objects in the reverse order, and in that process, will call the cleanup() function of each wrapper object, which in turn will delete the actual object. 18

19 Contents 1 Introduction 1 2 The Problem 1 3 Techniques to avoid static initializer ordering problem Avoid global variables of non-primitive datatypes Use a lazy allocation technique Replace the global variable with a global pointer that will be dynamically allocated when it is needed Modification of the previous technique, with a workaround to avoid memory leaks Use a local static object (Meyers Singleton) Force the global objects into the same compilation unit Use a static member of many static variables The Nifty Counter approach Solve the problem in the client application, rather than the library Avoid accessing a global object from a constructor Use a lazy-allocation singleton technique to defer the construction of the client object Recommended solutions Solutions that does not break the shared library compatibility Permanent solution that may break shared library compatibility constraint Further issues - Thread safety, order of destruction Making Meyers singleton technique thread-safe Forcing the destruction order of objects to be the opposite of construction order

COMP6771 Advanced C++ Programming

COMP6771 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 information

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file? QUIZ on Ch.5 Why is it sometimes not a good idea to place the private part of the interface in a header file? Example projects where we don t want the implementation visible to the client programmer: The

More information

Short Notes of CS201

Short 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 information

The issues. Programming in C++ Common storage modes. Static storage in C++ Session 8 Memory Management

The 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 information

CS201 - Introduction to Programming Glossary By

CS201 - 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 information

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading How C++ Works 1 Overview Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading Motivation There are lot of myths about C++

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 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 information

COMP6771 Advanced C++ Programming

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 information

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I Polynomial Class Polynomial(); Polynomial(const string& N, const vector& C); Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const

More information

Exception Safe Coding

Exception 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 information

CSE 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++ 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 information

Object-Oriented Programming for Scientific Computing

Object-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 information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

DYNAMIC MEMORY ALLOCATION ON REAL-TIME LINUX

DYNAMIC MEMORY ALLOCATION ON REAL-TIME LINUX DYNAMIC MEMORY ALLOCATION ON REAL-TIME LINUX Jianping Shen Institut Dr. Foerster GmbH und Co. KG In Laisen 70, 72766, Reutlingen, Germany shen.jianping@foerstergroup.de Michael Hamal Institut Dr. Foerster

More information

QUIZ Friends class Y;

QUIZ Friends class Y; QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They

More information

THE BIG FOUR FRIEND FUNCTIONS

THE BIG FOUR FRIEND FUNCTIONS er THE BIG FOUR FRIEND FUNCTIONS Problem Solving with Computers-II Read the syllabus. Know what s required. Know how to get help. CLICKERS OUT Freq Af How is h01 (specifically the CS16 final) going? A.

More information

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011 More C++ David Chisnall March 17, 2011 Exceptions A more fashionable goto Provides a second way of sending an error condition up the stack until it can be handled Lets intervening stack frames ignore errors

More information

CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers

CSCI-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 information

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

CSCI-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 information

Homework 4. Any questions?

Homework 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 information

CSE 333 Midterm Exam Cinco de Mayo, 2017 (May 5) Name UW ID#

CSE 333 Midterm Exam Cinco de Mayo, 2017 (May 5) Name UW ID# Name UW ID# There are 6 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. Ch. 14: Inheritance

More information

C++ Programming Lecture 4 Software Engineering Group

C++ 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 information

The basic operations defined on a symbol table include: free to remove all entries and free the storage of a symbol table

The basic operations defined on a symbol table include: free to remove all entries and free the storage of a symbol table SYMBOL TABLE: A symbol table is a data structure used by a language translator such as a compiler or interpreter, where each identifier in a program's source code is associated with information relating

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 9 Multithreading (continued) 2016 www.cse.unsw.edu.au/ cs6771 2. So Far Program Workflows: Sequential, Parallel, Embarrassingly Parallel Memory: Shared Memory,

More information

6 Architecture of C++ programs

6 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 information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

More information

Objects Managing a Resource

Objects 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 information

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary

Slide Set 14. for ENCM 339 Fall Steve Norman, PhD, PEng. Electrical & Computer Engineering Schulich School of Engineering University of Calgary Slide Set 14 for ENCM 339 Fall 2016 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary November 2016 ENCM 339 Fall 2016 Slide Set 14 slide 2/35

More information

Multimedia-Programmierung Übung 3

Multimedia-Programmierung Übung 3 Multimedia-Programmierung Übung 3 Ludwig-Maximilians-Universität München Sommersemester 2016 Ludwig-Maximilians-Universität München Multimedia-Programmierung 1-1 Today Ludwig-Maximilians-Universität München

More information

CSCI-1200 Data Structures Fall 2009 Lecture 25 Concurrency & Asynchronous Computing

CSCI-1200 Data Structures Fall 2009 Lecture 25 Concurrency & Asynchronous Computing CSCI-1200 Data Structures Fall 2009 Lecture 25 Concurrency & Asynchronous Computing Final Exam General Information The final exam will be held Monday, Dec 21st, 2009, 11:30am-2:30pm, DCC 308. A makeup

More information

Object-Oriented Programming for Scientific Computing

Object-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 information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 22 Shared-Memory Concurrency 1 Administrivia HW7 due Thursday night, 11 pm (+ late days if you still have any & want to use them) Course

More information

CS 160: Interactive Programming

CS 160: Interactive Programming CS 160: Interactive Programming Professor John Canny 3/8/2006 1 Outline Callbacks and Delegates Multi-threaded programming Model-view controller 3/8/2006 2 Callbacks Your code Myclass data method1 method2

More information

CS102 C++ Exception Handling & Namespaces

CS102 C++ Exception Handling & Namespaces CS102 C++ Exception Handling & Namespaces Bill Cheng http://merlot.usc.edu/cs102-s12 1 Topics to cover C Structs (Ch 10) C++ Classes (Ch 11) Constructors Destructors Member functions Exception Handling

More information

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; } Multiple choice questions, 2 point each: 1. What output is produced by the following program? #include int f (int a, int &b) a = b + 1; b = 2 * b; return a + b; int main( ) int x=1, y=2, z=3;

More information

2 ADT Programming User-defined abstract data types

2 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 information

Design Patterns in C++

Design Patterns in C++ Design Patterns in C++ Safety to exceptions Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa April 15, 2011 G. Lipari (Scuola Superiore Sant Anna) Exception Safety April 15,

More information

JAVA An overview for C++ programmers

JAVA An overview for C++ programmers JAVA An overview for C++ programmers Wagner Truppel wagner@cs.ucr.edu edu March 1st, 2004 The early history James Gosling, Sun Microsystems Not the usual start for a prog.. language Consumer electronics,

More information

Object Oriented Software Design - II

Object Oriented Software Design - II Object Oriented Software Design - II Safety to exceptions Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa April 12, 2012 G. Lipari (Scuola Superiore Sant Anna) Exception Safety

More information

Programming Style and Optimisations - An Overview

Programming Style and Optimisations - An Overview Programming Style and Optimisations - An Overview Summary In this lesson we introduce some of the style and optimization features you may find useful to understand as a C++ Programmer. Note however this

More information

Financial computing with C++

Financial computing with C++ Financial Computing with C++, Lecture 6 - p1/24 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 6 - p2/24 Outline Linked lists Linked

More information

CSE 303: Concepts and Tools for Software Development

CSE 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 information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

Operator overloading. Conversions. friend. inline

Operator overloading. Conversions. friend. inline Operator overloading Conversions friend inline. Operator Overloading Operators like +, -, *, are actually methods, and can be overloaded. Syntactic sugar. What is it good for - 1 Natural usage. compare:

More information

Memory Organization. The machine code and data associated with it are in the code segment

Memory Organization. The machine code and data associated with it are in the code segment Memory Management Memory Organization During run time, variables can be stored in one of three pools : 1. Stack 2. Global area (Static heap) 3. Dynamic heap The machine code and data associated with it

More information

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator C++ Addendum: Inheritance of Special Member Functions Constructors Destructor Construction and Destruction Order Assignment Operator What s s Not Inherited? The following methods are not inherited: Constructors

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

ECE 449 OOP and Computer Simulation Lecture 14 Final Exam Review

ECE 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 information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

A Whirlwind Tour of C++

A Whirlwind Tour of C++ Robert P. Goddard Applied Physics Laboratory University of Washington Part 1: 3 November 2000: Object Model Part 2: 17 November 2000: Templates Part 3: 15 December 2000: STL Part 4: 30 March 2001 Exceptions

More information

CS11 Introduction to C++ Fall Lecture 7

CS11 Introduction to C++ Fall Lecture 7 CS11 Introduction to C++ Fall 2012-2013 Lecture 7 Computer Strategy Game n Want to write a turn-based strategy game for the computer n Need different kinds of units for the game Different capabilities,

More information

N2880 Distilled, and a New Issue With Function Statics

N2880 Distilled, and a New Issue With Function Statics Doc No: SC22/WG21/N2917 = PL22.16/09-0107 Date: 2009-06-19 Project: Reply to: JTC1.22.32 Herb Sutter Microsoft Corp. 1 Microsoft Way Redmond WA USA 98052 Email: hsutter@microsoft.com This paper is an attempt

More information

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100 ECE 2035(A) Programming for Hardware/Software Systems Fall 2013 Exam Three November 20 th 2013 Name: Q1: /8 Q2: /30 Q3: /30 Q4: /32 Total: /100 1/10 For functional call related questions, let s assume

More information

A brief introduction to C++

A 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 information

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions C++: Const Function Overloading Constructors and Destructors Enumerations Assertions Const const float pi=3.14159; const int* pheight; // defines pointer to // constant int value cannot be changed // pointer

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

CSE 333 Lecture smart pointers

CSE 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 information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

SERIOUS ABOUT SOFTWARE. Qt Core features. Timo Strömmer, May 26,

SERIOUS ABOUT SOFTWARE. Qt Core features. Timo Strömmer, May 26, SERIOUS ABOUT SOFTWARE Qt Core features Timo Strömmer, May 26, 2010 1 Contents C++ refresher Core features Object model Signals & slots Event loop Shared data Strings Containers Private implementation

More information

Starting to Program in C++ (Basics & I/O)

Starting to Program in C++ (Basics & I/O) Copyright by Bruce A. Draper. 2017, All Rights Reserved. Starting to Program in C++ (Basics & I/O) On Tuesday of this week, we started learning C++ by example. We gave you both the Complex class code and

More information

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

An Introduction to C++

An Introduction to C++ An Introduction to C++ Introduction to C++ C++ classes C++ class details To create a complex type in C In the.h file Define structs to store data Declare function prototypes The.h file serves as the interface

More information

September 10,

September 10, September 10, 2013 1 Bjarne Stroustrup, AT&T Bell Labs, early 80s cfront original C++ to C translator Difficult to debug Potentially inefficient Many native compilers exist today C++ is mostly upward compatible

More information

Compiler Construction D7011E

Compiler Construction D7011E Compiler Construction D7011E Lecture 14: Memory Management Viktor Leijon Slides largely by Johan Nordlander with material generously provided by Mark P. Jones. 1 First: Run-time Systems 2 The Final Component:

More information

Kakadu and Java. David Taubman, UNSW June 3, 2003

Kakadu and Java. David Taubman, UNSW June 3, 2003 Kakadu and Java David Taubman, UNSW June 3, 2003 1 Brief Summary The Kakadu software framework is implemented in C++ using a fairly rigorous object oriented design strategy. All classes which are intended

More information

Lab 2: ADT Design & Implementation

Lab 2: ADT Design & Implementation Lab 2: ADT Design & Implementation By Dr. Yingwu Zhu, Seattle University 1. Goals In this lab, you are required to use a dynamic array to design and implement an ADT SortedList that maintains a sorted

More information

Class Destructors constant member functions

Class Destructors constant member functions Dynamic Memory Management Class Destructors constant member functions Shahram Rahatlou Corso di Programmazione++ Roma, 6 April 2009 Using Class Constructors #include Using std::vector; Datum average(vector&

More information

CSE 333 Lecture smart pointers

CSE 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 information

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s Session 2 - Classes in C++ Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) A C++ source file may contain: include directives #include

More information

Lecture 14: more class, C++ streams

Lecture 14: more class, C++ streams CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 14:

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 31 Static Members Welcome to Module 16 of Programming in C++.

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading HOW C++ WORKS Overview Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading Motivation There are lot of myths about C++

More information

Fast Introduction to Object Oriented Programming and C++

Fast 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 information

Creating a String Data Type in C

Creating a String Data Type in C C Programming Creating a String Data Type in C For this assignment, you will use the struct mechanism in C to implement a data type that models a character string: struct _String { char data; dynamically-allocated

More information

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS121/IS223. Object Reference Variables. Dr Olly Gotel CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223

More information

Lecture 15a Persistent Memory & Shared Pointers

Lecture 15a Persistent Memory & Shared Pointers Lecture 15a Persistent Memory & Shared Pointers Dec. 5 th, 2017 Jack Applin, Guest Lecturer 2017-12-04 CS253 Fall 2017 Jack Applin & Bruce Draper 1 Announcements PA9 is due today Recitation : extra help

More information

CSC1322 Object-Oriented Programming Concepts

CSC1322 Object-Oriented Programming Concepts CSC1322 Object-Oriented Programming Concepts Instructor: Yukong Zhang February 18, 2016 Fundamental Concepts: The following is a summary of the fundamental concepts of object-oriented programming in C++.

More information

Part III. Advanced C ++

Part 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 information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

Documentation. Programming / Documentation Slide 42

Documentation.   Programming / Documentation Slide 42 Documentation http://www.math.upb.de/~robsy/lehre/programmierkurs2008/ Programming / Documentation Slide 42 Memory Management (I) There are several types of memory which a program can access: Stack Every

More information

Part X. Advanced C ++

Part 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 information

Safety SPL/2010 SPL/20 1

Safety SPL/2010 SPL/20 1 Safety 1 system designing for concurrent execution environments system: collection of objects and their interactions system properties: Safety - nothing bad ever happens Liveness - anything ever happens

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer October 10, 2016 OOPP / C++ Lecture 7... 1/15 Construction and Destruction Kinds of Constructors Move Semantics OOPP / C++ Lecture 7... 2/15

More information

Bounding Object Instantiations, Part 2

Bounding Object Instantiations, Part 2 This is a pre-publication draft of the column I wrote for the June 1995 issue of the C++ Report. Pre-publication means this is what I sent to the Report, but it may not be exactly the same as what appeared

More information

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. QUIZ How

More information

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS

INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS INITIALISING POINTER VARIABLES; DYNAMIC VARIABLES; OPERATIONS ON POINTERS Pages 792 to 800 Anna Rakitianskaia, University of Pretoria INITIALISING POINTER VARIABLES Pointer variables are declared by putting

More information

Midterm Review. PIC 10B Spring 2018

Midterm 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 information

4.1 Introduction Programming preliminaries Constructors Destructors An example... 3

4.1 Introduction Programming preliminaries Constructors Destructors An example... 3 Department of Computer Science Tackling Design Patterns Chapter 4: Factory Method design pattern Copyright c 2016 by Linda Marshall and Vreda Pieterse. All rights reserved. Contents 4.1 Introduction.................................

More information

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1 COMP6771 Advanced C++ Programming Week 11 Object Oriented Programming 2016 www.cse.unsw.edu.au/ cs6771 2 Covariants and Contravariants Let us assume that Class B is a subtype of class A. Covariants:

More information

17. Classes. Encapsulation: public / private. Member Functions: Declaration. Member Functions: Call. class rational { int n; int d; // INV: d!

17. Classes. Encapsulation: public / private. Member Functions: Declaration. Member Functions: Call. class rational { int n; int d; // INV: d! Encapsulation: public / private 7. Classes Classes, Member Functions, Constructors, Stack, Linked List, Dynamic Memory, Copy-Constructor, Assignment Operator, Concept Dynamic Datatype class rational int

More information

CSE 333 Section 9 - pthreads

CSE 333 Section 9 - pthreads CSE 333 Section 9 - pthreads Welcome back to section! We re glad that you re here :) Process A process has a virtual address space. Each process is started with a single thread, but can create additional

More information

CSE 333 Lecture smart pointers

CSE 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 information

Structs. Contiguously-allocated region of memory Refer to members within structure by names Members may be of different types Example: Memory Layout

Structs. Contiguously-allocated region of memory Refer to members within structure by names Members may be of different types Example: Memory Layout Structs (C,C++) 2 Structs Contiguously-allocated region of memory Refer to members within structure by names Members may be of different types Example: struct rec int i; int a[3]; int *p; Memory Layout

More information

CS 241 Honors Memory

CS 241 Honors Memory CS 241 Honors Memory Ben Kurtovic Atul Sandur Bhuvan Venkatesh Brian Zhou Kevin Hong University of Illinois Urbana Champaign February 20, 2018 CS 241 Course Staff (UIUC) Memory February 20, 2018 1 / 35

More information

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103

More information

CS11 Intro C++ Spring 2018 Lecture 3

CS11 Intro C++ Spring 2018 Lecture 3 CS11 Intro C++ Spring 2018 Lecture 3 C++ File I/O We have already seen C++ stream I/O #include cout > name; cout

More information

Digging into the GAT API

Digging into the GAT API Digging into the GAT API Comparing C, C++ and Python API s Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/~gallen/teaching Digging into the GAT API Design Principles Object orientation Derivation,

More information