ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II

Size: px
Start display at page:

Download "ECE 449 OOP and Computer Simulation Lecture 12 Resource Management II"

Transcription

1 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 and Computer Engineering Illinois Institute of Technology November 10, 2017

2 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 2/62 Outline Smart Pointers Reference Counting and shared ptr Activities Abstraction by Polymorphism Issues with Our Implementation Abstraction by Runtime Polymorphism Handle Incomplete Types and Derived Types Beyond Memory Management

3 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 3/62 Reading Assignment This lecture: 14 Next lecture: None

4 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 4/62 Outline Smart Pointers Reference Counting and shared ptr Activities Abstraction by Polymorphism Issues with Our Implementation Abstraction by Runtime Polymorphism Handle Incomplete Types and Derived Types Beyond Memory Management

5 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 5/62 Worry-Free Memory Management For our simulator, we know exactly when the objects created on the heap should be deleted. The deletes are centralized in dtors. For other applications, it is possible one cannot decide the exact place where objects should be deleted. It is now programmers responsibility to delete them correctly. That s impossible for the majority of the programmers garbage collection (GC) is a must Programmers decide when objects should be created on the heap. The compiler/runtime library decide when they should be deleted. Typical garbage collection algorithms Reachability analysis: reclaim memory when necessary Reference counting: delete an object immediately when it s no longer in use

6 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 6/62 Smart Pointers Smart pointers: class types that can be used as pointers but are smarter than built-in pointers. They will delete an object when it is no longer in use. Provide GC to C++ programs std::unique_ptr: keep a non-copyable pointer to an object It is straight-forward to determine when the object should be deleted in its dtor. std::shared_ptr: allow to share a pointer to an object Reference counting is used to determine when the object should be deleted.

7 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 7/62 Outline Smart Pointers Reference Counting and shared ptr Activities Abstraction by Polymorphism Issues with Our Implementation Abstraction by Runtime Polymorphism Handle Incomplete Types and Derived Types Beyond Memory Management

8 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 8/62 Reference Counting For each object created on the heap, we need to maintain a number indicating how many pointers points to it. The number is called the reference count, or the count. The object should be deleted when the count becomes 0. Where should we store the count? The count should be per object, and have the same lifetime as the object. We may ask each object to hold a count, but that s not a good solution. Solution: create the count on the heap and delete it when the object is deleted How should we update the count correctly? Manually when the pointer is copied/discarded? Too tedious and error prone Solution: wrap the pointer in a class so the count can be updated automatically

9 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 9/62 The shared ptr Class template<class T> class shared_ptr { T *p_; int *count_; ; // class shared_ptr<t> Let s define shared_ptr as a class template so it can be used for any type of pointers. count_ will maintain a pointer to the reference count, created on the heap.

10 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 10/62 Class Invariants template<class T> class shared_ptr { T *p_; int *count_; ; // class shared_ptr<t> Either both p_ and count_ are NULL, Or there are *count_ number of shared_ptr<t> objects holding the pointers pointing to *p_. Other pointers pointing to *p_ are not counted since one should access the object only through shared_ptr<t>.

11 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 11/62 Default Ctor template<class T> class shared_ptr { T *p_; int *count_; public: shared_ptr() : p_(null), count_(null) { ; // class shared_ptr<t> For default ctor, we can simply set the pointers to NULL.

12 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 12/62 Dtor template<class T> class shared_ptr { T *p_; int *count_; public: ~shared_ptr() { if (count_!= NULL) { --*count_; if (*count_ == 0) { delete p_; delete count_; ; // class shared_ptr<t> We should decrease the count by 1 in dtor since there is one less shared_ptr<t> object holding the pointers. The object and the count should be deleted when the count drops to 0.

13 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 13/62 Ctor template<class T> class shared_ptr { T *p_; int *count_; public: shared_ptr(t *p) { try { count_ = new int(1); // initialize the count to 1 p_ = p; catch () { delete p; throw; ; // class shared_ptr<t> If we fail to create the count on the heap, we should also delete the pointer. The user of the class shared_ptr<t> should not be bothered by such issue as if the creation of the object is failed.

14 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 14/62 Implicit Construction void some_function(const shared_ptr<int> &p); void another_function() { int i = 0; some_function(&i); Since a ctor of shared_ptr<t> would take a pointer to T as the argument, the above code is valid as the construction is done implicitly. But it s wrong the object is not created on the heap. Although we cannot prohibit someone to construct a shared_ptr<t> object from a pointer to an object not created on the heap, we should highlight the creation of the shared_ptr<t> objects by prohibiting such implicit construction.

15 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 15/62 explicit Construction template<class T> class shared_ptr { T *p_; int *count_; public: explicit shared_ptr(t *p) { ; // class shared_ptr<t> The explicit keyword indicates the construction through the ctor must be explicit. Note that for ctors with at least two parameters w/o default arguments, construction must be explicit and it is not necessary to use explicit.

16 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 16/62 shared ptr and new void some_function(const shared_ptr<int> &p); void another_function() { int i = 0; // some_function(&i); // won t compile some_function(shared_ptr<int>(&i)); // wrong some_function(shared_ptr<int>(new int(5)); // correct Programmers can quickly identify errors with highlighted constructions. If a shared_ptr<t> object is constructed and there is no new, then something could be wrong. It is also possible to enforce every new to be accompanied by a shared_ptr<t> construction.

17 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 17/62 Copy Ctor template<class T> class shared_ptr { T *p_; int *count_; public: shared_ptr(const shared_ptr<t> &sp) : p_(sp.p_), count_(sp.count_) { ++*count_; ; // class shared_ptr<t> For a built-in pointer, making a copy means to copy the address of the object instead of to copy the object itself. Same rule applies here we make a copy of the pointer to the object, and a copy of the pointer to the count. That s why we call shared_ptr<t> smart pointer. Need to increase count by 1 Note that the parameter of the copy ctor should use the exact type shared_ptr<t> instead of shared_ptr.

18 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 18/62 Assignment template<class T> class shared_ptr { T *p_; int *count_; public: shared_ptr<t> &operator=(shared_ptr<t> rhs_copy) { swap(rhs_copy); return *this; ; // class shared_ptr<t> For exception safety, let s use copy-and-swap. Note that both the return type and the parameter should use the exact type shared_ptr<t>.

19 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 19/62 Swap template<class T> class shared_ptr { T *p_; int *count_; public: void swap(shared_ptr<t> &sp) { std::swap(p_, sp.p_); std::swap(count_, sp.count_); ; // class shared_ptr<t> It s straight-forward: just swap the members.

20 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 20/62 Pointer Operations void some_function() { shared_ptr<std::string> p(new std::string); *p = "string"; // operator* p->size(); // operator-> We need to overload * and -> such that a smart pointer can be used like a built-in pointer. Pointer arithmetics are not supported since it points to an object but not an array of object.

21 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 21/62 Dereference template<class T> class shared_ptr { T *p_; int *count_; public: T &operator*() const { assert(p_!= NULL); return *p_; ; // class shared_ptr<t> * should return a reference to the object on heap. * won t change the pointer and thus can be a const member function.

22 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 22/62 Arrow template<class T> class shared_ptr { T *p_; int *count_; public: T *operator->() const { assert(p_!= NULL); return p_; ; // class shared_ptr<t> C++ allows to overload -> but not.. Unlike other operators, when -> is overloaded, the compiler would interpret p->size() as p.operator->()->size(). -> should return a pointer to the object on heap.

23 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 23/62 Accessor template<class T> class shared_ptr { T *p_; int *count_; public: T *get() const { return p_; ; // class shared_ptr<t> In case the pointer is needed, users can access it through get(). It should be used with care. Note that one can always access the pointer by taking the address of the reference returned by * so get() doesn t expose more information of the smart pointer.

24 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 24/62 Outline Smart Pointers Reference Counting and shared ptr Activities Abstraction by Polymorphism Issues with Our Implementation Abstraction by Runtime Polymorphism Handle Incomplete Types and Derived Types Beyond Memory Management

25 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 25/62 Activity I typedef shared_ptr<std::string> str_ptr; str_ptr create_string(std::string s) { return str_ptr(new std::string(s)); str_ptr some_function() { str_ptr sp_first = create_string("first"); str_ptr sp_second(new std::string("second")); str_ptr sp; sp = sp_first; sp_first = sp_second; return sp; What objects are created on the heap and when they are deleted?

26 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 26/62 Activity I: Step 1 str_ptr create_string(std::string s) { return str_ptr(new std::string(s)); str_ptr some_function() { str_ptr sp_first = create_string("first"); Assume copy ctor is not optimized away by the compiler. Let s use (str, count) to represent the object and its reference count on the heap. Inside create_string, a temporary str_ptr object is first created pointing to ("first", 1). It is then copied to the return value: the pair becomes ("first", 2). When the function returns, the temporary str_ptr object is destroyed: the pair becomes ("first", 1).

27 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 27/62 Activity I: Step 2 str_ptr some_function() { str_ptr sp_first = create_string("first"); str_ptr sp_second(new std::string("second")); str_ptr sp; The return value of create_string is copied to sp_first: the pair becomes ("first", 2). A new pair ("second", 1) is created and pointed by sp_second. sp holds NULL members.

28 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 28/62 Activity I: Step 3 str_ptr some_function() { str_ptr sp_first = create_string("first"); str_ptr sp_second(new std::string("second")); str_ptr sp; sp = sp_first; sp_first = sp_second; sp_first is assigned to sp: both of them point to the pair ("first", 3) The return value of create_string is not destroyed yet that s the third smart pointer pointing to the pair. sp_second is assigned to sp_first: both of them point to the pair ("second", 2) The reference count to "first" is decreased by 1 to 2. sp and the return value of create_string point to the pair ("first", 2).

29 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 29/62 Activity I: Step 4 str_ptr some_function() { str_ptr sp_first = create_string("first"); str_ptr sp_second(new std::string("second")); str_ptr sp; sp = sp_first; sp_first = sp_second; return sp; sp is copied to the return value of some_function: the pair they point to becomes ("first", 3). What happens when some_function returns? Local variables are destroyed in the reverse order of construction.

30 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 30/62 Activity I: Step 5 str_ptr some_function() { str_ptr sp_first = create_string("first"); str_ptr sp_second(new std::string("second")); str_ptr sp; return sp; Before some_function returns, ("first", 3): sp, return value of some_function, return value of create_string ("second", 2): sp_first, sp_second sp is destroyed: ("first", 2). sp_second is destroyed: ("second", 1) sp_first is destroyed: ("second", 0) The pair is then deleted from the heap. Return value of create_string is destroyed: ("first", 1) Finally, we only have the pair ("first", 1), which is pointed by the return value of some_function.

31 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 31/62 Activity II struct B; struct A { shared_ptr<b> b_of_a; ; // struct A struct B { shared_ptr<a> a_of_b; ; // struct B void some_function() { shared_ptr<a> pa(new A); shared_ptr<b> pb(new B); pa->b_of_a = pb; pb->a_of_b = pa; Any thing wrong?

32 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 32/62 Activity II: Cycles Lead to Memory Leakage struct B; struct A { shared_ptr<b> b_of_a; ; // struct A struct B { shared_ptr<a> a_of_b; ; // struct B void some_function() { shared_ptr<a> pa(new A); // (A, 1) shared_ptr<b> pb(new B); // (A, 1), (B, 1) pa->b_of_a = pb; // (A, 1), (B, 2) pb->a_of_b = pa; // (A, 2), (B, 2) // pb is destroyed: (A, 2), (B, 1) // pa is destroyed: (A, 1), (B, 1) Memory leakage! Limitation of reference counting based smart pointers: at runtime, if the smart pointers form a cycle, resources won t be released properly.

33 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 33/62 Outline Smart Pointers Reference Counting and shared ptr Activities Abstraction by Polymorphism Issues with Our Implementation Abstraction by Runtime Polymorphism Handle Incomplete Types and Derived Types Beyond Memory Management

34 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 34/62 Outline Smart Pointers Reference Counting and shared ptr Activities Abstraction by Polymorphism Issues with Our Implementation Abstraction by Runtime Polymorphism Handle Incomplete Types and Derived Types Beyond Memory Management

35 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 35/62 Pointers and Incomplete Types class A; // forward declaration bool operation_one(a *p); void operation_two(a *p); void combined_operation(a *p) { if (operation_one(p)) { operation_two(p); You can implement combined_operation without knowing anything about A. In this context, the type A is incomplete. Using incomplete types is a typical method to hide all implementation details. Especially for C where OO is not supported directly, e.g. FILE *

36 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 36/62 Smart Pointers and Incomplete Types class A; // forward declaration bool operation_one(shared_ptr<a> p); void operation_two(shared_ptr<a> p); void combined_operation(shared_ptr<a> p) { if (operation_one(p)) { operation_two(p); What if we replace A * with shared_ptr<a> as implemented in the last lecture? The code won t compile. When combined_operation returns, the dtor of shared_ptr<a> will be called. Since the dtor of shared_ptr<a> is a member of a class template, it is instantiated here. It need to access the dtor of A for delete, but that s not available since A is incomplete.

37 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 37/62 Pointers and Derived Types class derived : public base { ; // class derived bool base_operation(base *p); void some_function(derived *p) { if (base_operation(p)) { // do something here Implicit conversion works here to convert a derived pointer to a base pointer.

38 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 38/62 Smart Pointers and Derived Types I template<class T> class shared_ptr { T *p_; int *count_; public: template <class U> shared_ptr(const shared_ptr<u> &sp) : p_(sp.p_), // ensure U is T or derived from T count_(sp.count_) { ++*count_; ; // class shared_ptr<t> We can enable the implicit conversion among smart pointers by introducing a template ctor to replace the copy ctor. Note that if U is not T or is not actually derived from T (except T is void), then p_(sp.p_) won t compile.

39 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 39/62 Smart Pointers and Derived Types II bool base_operation(shared_ptr<base> p); void some_function(shared_ptr<derived> p) { if (base_operation(p)) { // do something here In such case, there is a chance the derived object will be deleted through the base pointer. If the dtor of base is not virtual, memory leakage may happen. C++ does allow a base class to have a dtor not being virtual.

40 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 40/62 Pointers and Smart Pointers Our implementation of shared_ptr is not quite like built-in pointers Need a complete type when used Cannot handle derived objects with base pointers As the issues are both with the delete in dtor, can we modify the implementation to address them? In addition, can we use the same idea to manage resources not on heap? Store a pointer to a local object (with care) in shared_ptr Use shared_ptr to manage resources like FILE *

41 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 41/62 Outline Smart Pointers Reference Counting and shared ptr Activities Abstraction by Polymorphism Issues with Our Implementation Abstraction by Runtime Polymorphism Handle Incomplete Types and Derived Types Beyond Memory Management

42 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 42/62 delete and Abstraction ~shared_ptr() { if (count_!= NULL) { --*count_; if (*count_ == 0) { delete p_; delete count_; // <=========== here is the problem All issues happen when we attempt to delete a pointer in the dtor of shared_ptr. We need to make sure we are deleting the pointer with the correct type. Or don t delete at all if the resource is not on heap We need an abstraction of deletion to hide how the resource should be deleted/released.

43 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 43/62 Abstraction by Runtime Polymorphism class ref_count { ref_count(const ref_count &) = delete; ref_count &operator=(const ref_count &) = delete; virtual void destroy() = 0; int count_; public: void inc_ref(); void dec_ref(); protected: ref_count() : count_(1) { virtual ~ref_count() { ; // class ref_count The abstraction could be defined through the pure virtual function destroy. Follow the template method pattern, the reference count is managed in the same class. The template methods are inc_ref and dec_ref.

44 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 44/62 Implement inc ref and dec ref class ref_count { void inc_ref() { ++count_; void dec_ref() { --count_; if (count_ == 0) { destroy(); delete this; ; // class ref_count The virtual dtor ensures derived objects of ref_count will be deleted correctly through ref_count pointers. These two functions can be further tweaked for multi-threaded programs/ multi-core platforms.

45 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 45/62 Updated shared ptr Class template<class T> class shared_ptr { T *p_; ref_count *count_; public: template <class U> shared_ptr(const shared_ptr<u> &sp) : p_(sp.p_), count_(sp.count_) { count_->inc_ref(); ~shared_ptr() { if (count_!= NULL) count_->dec_ref(); ; // class shared_ptr<t> The data member for reference count, the template ctor, and the dtor should be updated. All other members except shared_ptr(t *p) remain the same.

46 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 46/62 Outline Smart Pointers Reference Counting and shared ptr Activities Abstraction by Polymorphism Issues with Our Implementation Abstraction by Runtime Polymorphism Handle Incomplete Types and Derived Types Beyond Memory Management

47 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 47/62 Resources on Heap template <class T> class ref_count_heap : public ref_count { T *p_; virtual void destroy() { delete p_; public: ref_count_t(t *p) : p_(p) { ; // class ref_count_heap<t> For resources on heap, the ref_count_heap<t> class is designed. It should hold a pointer to the object of type T on heap. The destroy function implements how the object should be deleted. We do need more storage for a ref_count_heap<t> object than a simple int. There is always trade-offs in your design. Here we prefer usability since the storage overhead is acceptable.

48 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 48/62 Updated Ctor template<class T> class shared_ptr { T *p_; ref_count *count_; public: explicit shared_ptr(t *p) { try { count_ = new ref_count_heap<t>(p); p_ = p; catch () { delete p; throw; ; // class shared_ptr<t> Note that we use the base pointer count_ to store a derived object created by new on heap.

49 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 49/62 Construction with a Complete Type template<class T> class shared_ptr { explicit shared_ptr(t *p) { count_ = new ref_count_heap<t>(p); delete p; ; // class shared_ptr<t> shared_ptr<a> create_object() { return shared_ptr<a>(new A); shared_ptr(t *p) is instantiated when called. At that point, the type T (A) should be complete since we expect *p to be created on the heap in the same statement. delete p should compile without a problem. ref_count_heap<t> is instantiated at the line count_=

50 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 50/62 Instantiation of ref count heap<t> count_ = new ref_count_heap<t>(p); For a class template, the data members are instantiated when an object of the class is referred to; an member function is instantiated when they are referred to. For the above line, clearly it would lead to the instantiation of the data members and the ctor. The dtor and destroy will be referred within the ctor as they are virtual. So they are also instantiated here. As the type T (A) is complete here, destroy will compile correctly.

51 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 51/62 Handle Incomplete Types class A; // forward declaration bool operation_one(shared_ptr<a> p); void operation_two(shared_ptr<a> p); void combined_operation(shared_ptr<a> p) { if (operation_one(p)) { operation_two(p); The dtor of shared_ptr<a> may eventually call the virtual function destroy of ref_count to release the object. The compiler don t need to instantiate ref_count_heap<a>::destroy here and don t need to know the complete type of A here. Is count_ pointing to a ref_count_heap<a> object? No more compiling error!

52 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 52/62 Handle Derived Types template<class T> class shared_ptr { template <class U> shared_ptr(const shared_ptr<u> &sp) : p_(sp.p_), count_(sp.count_) { count_->inc_ref(); ; // class shared_ptr<t> count_ will point to an object that knows the exact type of p_. We ll always release the object pointed by p_ through a pointer of its actual type. No memory leakage!

53 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 53/62 Assignment and Derived Types void some_function() { shared_ptr<derived> sp_derived(new derived); shared_ptr<base> sp_base; sp_base = sp_derived; // will it work? Do we need to implement a template operator= to support the assignment? shared_ptr<base>::operator= asks for an argument of type const shared_ptr<base> &. The compiler will use the template ctor to construct a shared_ptr<base> object from sp_derived. It compiles and works correctly with the current implementation.

54 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 54/62 What if shared_ptr<base> create_derived_object() { return shared_ptr<base>(new derived); The pointer to the derived object will be converted to a base pointer implicitly. Memory leakage may happen. I know you can implement the function as shared_ptr<base> create_derived_object() { return shared_ptr<derived>(new derived); But what if someone forgot to do so?

55 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 55/62 Another Template Ctor template<class T> class shared_ptr { template <class U> explicit shared_ptr(u *p) { try { count_ = new ref_count_heap<u>(p); p_ = p; // ensure U is T or derived from T catch () { delete p; // another place that need the exact type of p throw; ; // class shared_ptr<t> By extending the ctor shared_ptr(t *p) to a template, we can obtain the exact argument type for construction. The type information is then used to create the correct ref_count_heap object on heap.

56 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 56/62 Outline Smart Pointers Reference Counting and shared ptr Activities Abstraction by Polymorphism Issues with Our Implementation Abstraction by Runtime Polymorphism Handle Incomplete Types and Derived Types Beyond Memory Management

57 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 57/62 Deleters template <class T, class D> class ref_count_deleter : public ref_count { T *p_; D deleter_; virtual void destroy() { deleter_(p_); public: ref_count_t(t *p, D d) : p_(p), deleter_(d) { ; // class ref_count_deleter<d> We can further generalize delete by a deleter. For now, let s say a deleter is a function that releases a kind of resources not created on heap. We can derive the class ref_count_deleter<t,d> from ref_count where D is the type of the deleter function. As we will see later, type argument deduction will be leveraged to generate the type D and we don t need to specify it explicitly.

58 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 58/62 Template Ctor and Deleters template<class T> class shared_ptr { template <class U, class D> shared_ptr(u *p, D d) { try { count_ = new ref_count_deleter<u, D>(p, d); p_ = p; catch () { d(p); // if fails, we release p using the deleter d throw; ; // class shared_ptr<t> Similar to template <class U> shared_ptr(u *p), we can obtain the exact argument types for construction with deleters by a template ctor. The types U and D are used to create the correct ref_count_deleter object on heap.

59 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 59/62 Example I: Local Objects void null_deleter(void *) { // do nothing void some_operation(shared_ptr<a> p); void some_function() { A a; shared_ptr<a> sp0(&a, null_deleter); some_operation(sp0); shared_ptr<a> sp1(new A); some_operation(sp1); sp1 = sp0; sp0 = shared_ptr<a>(new A); With a deleter that does nothing, we can store a pointer to a local object in shared_ptr. Be careful for its lifetime. It can be use together with the smart pointers with objects created on heap. The derived classes of ref_count will make sure all objects are deleted correctly.

60 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 60/62 Example II: Objects not on Heap void some_function() { shared_ptr<file> f(fopen("data.txt", "r"), fclose); file_operation(f); The file will be closed when it is no longer in use.

61 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 61/62 Example III: Clean-ups and Exception Safety void some_function() { shared_ptr<void> p(malloc(1000), free); if () { return; else if () { return; Clean-ups are done automatically. Also guarantee exception safety It is the easiest way to bridge your C++ code with libraries that provide a C interface.

62 ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 62/62 Summary and Advice std::shared_ptr provides reference counting based GC and resource management to C++ programs. It helps to improve the quality of application and should be used whenever you cannot determine the exact lifetime of an object. However, programmers should ensure no cycle may form at runtime to prevent resource leakage. Polymorphism is the key element in library design. Use runtime polymorphism to hide detailed type information so couplings are minimum Use compile-time polymorphism to extract detailed type information so cases can be handled in the correct way The two can be combined to achieve elegant solutions for many design problems.

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

ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns

ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/60 ECE 449 OOP and Computer Simulation Lecture 11 Design Patterns Professor Jia Wang Department of Electrical

More information

ECE 449 OOP and Computer Simulation Lecture 08 Resource Management I

ECE 449 OOP and Computer Simulation Lecture 08 Resource Management I ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/69 ECE 449 OOP and Computer Simulation Lecture 08 Resource Management I Professor Jia Wang Department of Electrical

More information

ECE 449 OOP and Computer Simulation Lecture 07 Class Design for Circuit Netlist

ECE 449 OOP and Computer Simulation Lecture 07 Class Design for Circuit Netlist ECE 449 Object-Oriented Programming and Computer Simulation, Fall 2017, Dept. of ECE, IIT 1/64 ECE 449 OOP and Computer Simulation Lecture 07 Class Design for Circuit Netlist Professor Jia Wang Department

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

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

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

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

AIMS Embedded Systems Programming MT 2017

AIMS Embedded Systems Programming MT 2017 AIMS Embedded Systems Programming MT 2017 Object-Oriented Programming with C++ Daniel Kroening University of Oxford, Computer Science Department Version 1.0, 2014 Outline Classes and Objects Constructors

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

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

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

Singleton, Factory Method, Abstract Factory, Named Constructor. Using one or more base classes to hide details from the client

Singleton, Factory Method, Abstract Factory, Named Constructor. Using one or more base classes to hide details from the client Idioms & Design Patterns Creational Introduction to Design Patterns Patterns and idioms can be grouped roughly into: Creational Patterns and idioms Singleton, Factory Method, Abstract Factory, Named Constructor

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

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

C++ Programming Lecture 7 Software Engineering Group

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

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level

More information

G52CPP C++ Programming Lecture 20

G52CPP C++ Programming Lecture 20 G52CPP C++ Programming Lecture 20 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Wrapping up Slicing Problem Smart pointers More C++ things Exams 2 The slicing problem 3 Objects are not

More information

Lecture Notes on Queues

Lecture Notes on Queues Lecture Notes on Queues 15-122: Principles of Imperative Computation Frank Pfenning Lecture 9 September 25, 2012 1 Introduction In this lecture we introduce queues as a data structure and linked lists

More information

ALL ABOUT POINTERS C/C++ POINTERS

ALL ABOUT POINTERS C/C++ POINTERS ALL ABOUT POINTERS CS 403: Pointers, References, and Management Stefan D. Bruda Fall 2017 http://xkcd.com/138/ CS 403: Pointers, References, and Management (S. D. Bruda) Fall 2017 1 / 27 POINTERS C/C++

More information

Engineering Robust Server Software

Engineering 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 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

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have

More information

G52CPP C++ Programming Lecture 16

G52CPP C++ Programming Lecture 16 G52CPP C++ Programming Lecture 16 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Casting static cast dynamic cast const cast reinterpret cast Implicit type conversion 2 How

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

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

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 4 Part One: (continued) and 2016 www.cse.unsw.edu.au/ cs6771 2. Inline Constructors, Accessors and Mutators Question (from 2015): In the week 3 examples, constructors

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

Structure of Programming Languages Lecture 10

Structure of Programming Languages Lecture 10 Structure of Programming Languages Lecture 10 CS 6636 4536 Spring 2017 CS 6636 4536 Lecture 10: Classes... 1/23 Spring 2017 1 / 23 Outline 1 1. Types Type Coercion and Conversion Type Classes, Generics,

More information

Class Information ANNOUCEMENTS

Class Information ANNOUCEMENTS Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to

More information

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

class Polynomial { public: Polynomial(const string& N = no name, const vector<int>& C = vector<int>());... }; Default Arguments 1 When declaring a C++ function, you may optionally specify a default value for function parameters by listing initializations for them in the declaration: class Polynomial { public:

More information

Structuur van Computerprogramma s 2

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

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

CS11 Advanced C++ Fall Lecture 3

CS11 Advanced C++ Fall Lecture 3 CS11 Advanced C++ Fall 2006-2007 Lecture 3 Today s Topics C++ Standard Exceptions Exception Cleanup Fun with Exceptions Exception Specifications C++ Exceptions Exceptions are nice for reporting many errors

More information

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. 1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

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

A Generic Non-intrusive Smart Pointer Implementation

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

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

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

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

Constraining unique_ptr

Constraining unique_ptr Constraining unique_ptr Document: N2853=09-0043 Date: 2009-03-20 Reply to: Alisdair Meredith public@alisdairm.net Introduction Unique_ptr is a new class template introduced in C++0x to simplify the use

More information

MODERN AND LUCID C++ ADVANCED

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

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

C++ Primer for CS175

C++ Primer for CS175 C++ Primer for CS175 Yuanchen Zhu September 10, 2014 This primer is pretty long and might scare you. Don t worry! To do the assignments you don t need to understand every point made here. However this

More information

04-19 Discussion Notes

04-19 Discussion Notes 04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here

More information

Increases Program Structure which results in greater reliability. Polymorphism

Increases Program Structure which results in greater reliability. Polymorphism UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the

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

Dynamic Memory Allocation

Dynamic Memory Allocation Dynamic Memory Allocation Lecture 15 COP 3014 Fall 2017 November 6, 2017 Allocating memory There are two ways that memory gets allocated for data storage: 1. Compile Time (or static) Allocation Memory

More information

Virtual functions concepts

Virtual functions concepts Virtual functions concepts l Virtual: exists in essence though not in fact l Idea is that a virtual function can be used before it is defined And it might be defined many, many ways! l Relates to OOP concept

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Explicit Conversion Operator Draft Working Paper

Explicit Conversion Operator Draft Working Paper Explicit Conversion Operator Draft Working Paper Lois Goldthwaite, Michael Wong IBM michaelw@ca.ibm.com ACCU Lois@LoisGoldthwaite.com Document number: N2223=07-0083 Date: 2007-03-11 Project: Programming

More information

Introduce C# as Object Oriented programming language. Explain, tokens,

Introduce C# as Object Oriented programming language. Explain, tokens, Module 2 98 Assignment 1 Introduce C# as Object Oriented programming language. Explain, tokens, lexicals and control flow constructs. 99 The C# Family Tree C Platform Independence C++ Object Orientation

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

Pointers. Developed By Ms. K.M.Sanghavi

Pointers. 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 information

Lecture 10 Notes Linked Lists

Lecture 10 Notes Linked Lists Lecture 10 Notes Linked Lists 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, Rob Simmons, André Platzer 1 Introduction In this lecture we discuss the use of linked lists to

More information

Lecture 2: C Programm

Lecture 2: C Programm 0 3 E CS 1 Lecture 2: C Programm ing C Programming Procedural thought process No built in object abstractions data separate from methods/functions Low memory overhead compared to Java No overhead of classes

More information

C++ Modern and Lucid C++ for Professional Programmers

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

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

QUIZ How do we implement run-time constants and. compile-time constants inside classes? QUIZ How do we implement run-time constants and compile-time constants inside classes? Compile-time constants in classes The static keyword inside a class means there s only one instance, regardless of

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

C++ Smart Pointers. CSE 333 Autumn 2018

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

Doc. No.: WG21/N0937=X3J16/ Date: 28 May 1996 Project: C++ Standard Library Reply to: Nathan Myers

Doc. No.: WG21/N0937=X3J16/ Date: 28 May 1996 Project: C++ Standard Library Reply to: Nathan Myers Doc. No.: WG21/N0937=X3J16/96-0119 Date: 28 May 1996 Project: C++ Standard Library Reply to: Nathan Myers Clause 20 (Utilities Library) Issues (Revision 4) ** Revision History: Revision

More information

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued

Exception Safety. CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, Glenn G. Chappell. continued continued CS 311 Data Structures and Algorithms Lecture Slides Wednesday, October 28, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005

More information

1d: tests knowing about bitwise fields and union/struct differences.

1d: tests knowing about bitwise fields and union/struct differences. Question 1 1a: char ptr[] = Hello World ; char a = ptr[1], b = *(ptr+6); Creates an array of 12 elements, 11 visible letters and a character value 0 at the end. i true ii true iii false iv false v true

More information

use static size for this buffer

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

Value Semantics and Concept Based Polymorphism Sean Parent Principal Scientist Adobe Systems Incorporated. All Rights Reserved.

Value Semantics and Concept Based Polymorphism Sean Parent Principal Scientist Adobe Systems Incorporated. All Rights Reserved. Value Semantics and Concept Based Polymorphism Sean Parent Principal Scientist 2012 Adobe Systems Incorporated. All Rights Reserved. Outline of Talk Defining Value Semantics Polymorphic Types Demo of Photoshop

More information

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

CSE 333. Lecture 11 - constructor insanity. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington CSE 333 Lecture 11 - constructor insanity Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia Exercises: - New exercise out today, due Monday morning

More information

Vector and Free Store (Pointers and Memory Allocation)

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

CS61, Fall 2012 Section 2 Notes

CS61, Fall 2012 Section 2 Notes CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors

More information

Allocation & Efficiency Generic Containers Notes on Assignment 5

Allocation & Efficiency Generic Containers Notes on Assignment 5 Allocation & Efficiency Generic Containers Notes on Assignment 5 CS 311 Data Structures and Algorithms Lecture Slides Friday, October 30, 2009 Glenn G. Chappell Department of Computer Science University

More information

Programming, numerics and optimization

Programming, numerics and optimization Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

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

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

More class design with C++ Starting Savitch Chap. 11

More class design with C++ Starting Savitch Chap. 11 More class design with C++ Starting Savitch Chap. 11 Member or non-member function? l Class operations are typically implemented as member functions Declared inside class definition Can directly access

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

Lecture 8 Data Structures

Lecture 8 Data Structures Lecture 8 Data Structures 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning, André Platzer, Rob Simmons, Iliano Cervesato In this lecture we introduce the idea of imperative data

More information

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan

Operating Systems 2INC0 C course Pointer Advanced. Dr. Ir. Ion Barosan Operating Systems 2INC0 C course Pointer Advanced Dr. Ir. Ion Barosan (i.barosan@tue.nl) Containt Pointers Definition and Initilization Ponter Operators Pointer Arithmetic and Array Calling Functions by

More information

Smart Pointers. Some slides from Internet

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

RAII and Smart Pointers. Ali Malik

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

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

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

8 Understanding Subtyping

8 Understanding Subtyping Object-Oriented Design Lecture 8 CS 3500 Fall 2010 (Pucella) Friday/Tuesday, Oct 8/12, 2010 8 Understanding Subtyping Subtpying is a great way to enable client-side reuse, requiring a client to write a

More information

377 Student Guide to C++

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

Lecture 16: Static Semantics Overview 1

Lecture 16: Static Semantics Overview 1 Lecture 16: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis

More information

G52CPP C++ Programming Lecture 7. Dr Jason Atkin

G52CPP C++ Programming Lecture 7. Dr Jason Atkin G52CPP C++ Programming Lecture 7 Dr Jason Atkin 1 This lecture classes (and C++ structs) Member functions inline functions 2 Last lecture: predict the sizes 3 #pragma pack(1) #include struct A

More information

Hazard Pointers. Safe Resource Reclamation for Optimistic Concurrency

Hazard Pointers. Safe Resource Reclamation for Optimistic Concurrency Document Number: P0233R3 Date: 2017-02-06 Reply-to: maged.michael@acm.org, michael@codeplay.com Authors: Maged M. Michael, Michael Wong, Paul McKenney, Arthur O'Dwyer, David Hollman Project: Programming

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

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

CA31-1K DIS. Pointers. TA: You Lu

CA31-1K DIS. Pointers. TA: You Lu CA31-1K DIS Pointers TA: You Lu Pointers Recall that while we think of variables by their names like: int numbers; Computer likes to think of variables by their memory address: 0012FED4 A pointer is a

More information

Modern and Lucid C++ Advanced for Professional Programmers. Part 12 Advanced Library Design. Department I - C Plus Plus Advanced

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

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

Generalized pointer casts

Generalized pointer casts Contents Doc No: N3235=11-0005 Date: 2011-02-23 Authors: Pablo Halpern Intel Corp.. phalpern@halpernwightsoftware.com Generalized pointer casts National Body Comments and Issues... 1 Document Conventions...

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

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd.

C++11: 10 Features You Should be Using. Gordon R&D Runtime Engineer Codeplay Software Ltd. C++11: 10 Features You Should be Using Gordon Brown @AerialMantis R&D Runtime Engineer Codeplay Software Ltd. Agenda Default and Deleted Methods Static Assertions Delegated and Inherited Constructors Null

More information