0% found this document useful (0 votes)
9 views

Module 57

Uploaded by

deva.jntuk.cse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Module 57

Uploaded by

deva.jntuk.cse
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Module M57

L
Partha Pratim
Das
Programming in Modern C++

E
Objectives &
Outlines
Module M57: C++11 and beyond: Resource Management by Smart Pointers: Part 2

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy
Partha Pratim Das

N
Resource
Management
std::unique ptr
Department of Computer Science and Engineering
std::shared ptr
std::weak ptr
Indian Institute of Technology, Kharagpur
std::auto ptr
Summary [email protected]
Binary Tree

Recommendations
All url’s in this module have been accessed in September, 2021 and found to be functional
Module Summary

Programming in Modern C++ Partha Pratim Das M57.1


Module Recap

Module M57

• Revisited Raw Pointers and discussed how to deal with the objects through raw pointer

L
Partha Pratim
Das
• Introduced Smart pointers with typical interface and use

E
Objectives &
Outlines • Introduced some of the policies for smart pointer:

T
Smart Pointers
Recap
◦ Different storage policies
Ownership Policy
◦ Ownership Policies

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.2


Module Objectives

Module M57

• To continue Discussions on various policies of smart pointers

L
Partha Pratim
Das
◦ Ownership Policies

E
Objectives &
Outlines ◦ Implicit Conversion policy
◦ Null test policy

T
Smart Pointers
Recap
Ownership Policy • To familiarize with Resource Management using Smart Pointers from Standard Library

P
Conversion Policy
Null-test Policy ◦ unique ptr

N
Resource ◦ shared ptr
Management
std::unique ptr ◦ weak ptr
std::shared ptr
std::weak ptr
◦ auto ptr
std::auto ptr
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.3


Module Outline

Module M57
1 Smart Pointers

L
Partha Pratim
Das
Recap
Ownership Policy

E
Objectives &
Outlines
Conversion Policy

T
Smart Pointers
Recap Null-test Policy
Ownership Policy

P
Conversion Policy
Null-test Policy
2 Resource Management
std::unique ptr

N
Resource
Management std::shared ptr
std::unique ptr
std::shared ptr std::weak ptr
std::weak ptr
std::auto ptr std::auto ptr
Summary
Binary Tree
Summary of Smart Pointer Operations
Recommendations Binary Tree
Module Summary
3 Recommendations for Smart Pointers
4 Module Summary
Programming in Modern C++ Partha Pratim Das M57.4
Smart Pointers

Module M57
Sources:

L
Partha Pratim
Das
Chapter 4. Smart Pointers: Effective Modern C++, Scott Meyers
◦ Item 18: Use std::unique ptr for exclusive-ownership resource management
◦ Item 19: Use std::shared ptr for shared-ownership resource management

E
Objectives &
Outlines ◦ Item 20: Use std::weak ptr for std::shared ptr-like pointers that can dangle
◦ Item 21: Prefer std::make unique and std::make shared to direct use of new

T
Smart Pointers
Recap • The Rule of The Big Three (and a half) – Resource Management in C++, 2014
Ownership Policy

P
Smart pointer, wikipedia
Conversion Policy
• How to use C++ raw pointers properly?, Sorush Khajepor, 2020
Null-test Policy
• What is a C++ unique pointer and how is it used? smart pointers part I, Sorush Khajepor, 2021

N
Resource • What is a C++ shared pointer and how is it used? smart pointers part II, Sorush Khajepor, 2021
Management
• What is a C++ weak pointer and where is it used? smart pointers part III, Sorush Khajepor, 2021
std::unique ptr
std::shared ptr
• Lambdas: Smart Pointers, Jim Fix, Reed College
std::weak ptr
std::auto ptr
Summary
Binary Tree

Recommendations
Smart Pointers
Module Summary

Programming in Modern C++ Partha Pratim Das M57.5


Smart Pointers: Recap

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree Smart Pointers: Recap
Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.6


What is a Smart Pointer? (Recap Module 56)

Module M57

• A Smart pointer is a C++ object

L
Partha Pratim
Das
• Stores pointers to dynamically allocated (heap / free store) objects

E
Objectives &
Outlines • Improves raw pointers by implementing

T
Smart Pointers
Recap
◦ Construction & Destruction
Ownership Policy
◦ Copying & Assignment

P
Conversion Policy
Null-test Policy ◦ Dereferencing:

N
Resource
Management
. operator->
std::unique ptr . unary operator*
std::shared ptr
std::weak ptr
std::auto ptr
• Grossly mimics raw pointer syntax and semantics
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.7


Typical Tasks of a Smart Pointer (Recap Module 56)

Module M57

• Selectively disallows unwanted operations, that is, Address Arithmetic

L
Partha Pratim
Das
• Lifetime Management

E
Objectives &
Outlines ◦ Automatically deletes dynamically created objects at appropriate time
◦ On face of exceptions – ensures proper destruction of dynamically created objects

T
Smart Pointers
Recap
Ownership Policy
◦ Keeps track of dynamically allocated objects shared by multiple owners

P
Conversion Policy
Null-test Policy
• Concurrency Control
• Supports Idioms: RAII: Resource Acquisition is Initialization Idiom and RRID:

N
Resource
Management
std::unique ptr
Resource Release Is Destruction
std::shared ptr
std::weak ptr
◦ The idiom makes use of the fact that every time an object is created a constructor
std::auto ptr is called; and when that object goes out of scope a destructor is called
Summary
Binary Tree ◦ The constructor/destructor pair can be used to create an object that automatically
Recommendations allocates and initialises another object (known as the managed object) and cleans
Module Summary up the managed object when it (the manager) goes out of scope
◦ This mechanism is generically referred to as resource management

Programming in Modern C++ Partha Pratim Das M57.8


Typical Smart Pointer Interface (Recap Module 56)

Module M57
template<typename T> // Pointee type T
class SmartPtr {

L
Partha Pratim
Das
public:

E
Objectives & // Constructible
Outlines // No implicit conversion from Raw ptr

T
Smart Pointers explicit SmartPtr(T* pointee):
Recap
pointee_(pointee) { }
Ownership Policy

P
Conversion Policy
// Copy Constructible
Null-test Policy SmartPtr(const SmartPtr& other);

N
Resource // Assignable
Management SmartPtr& operator=(const SmartPtr& other);
std::unique ptr
std::shared ptr
// Destroys the pointee
std::weak ptr ~SmartPtr();
std::auto ptr // Dereferencing
Summary
Binary Tree
T& operator*() const { ... return *pointee_; }
Recommendations
// Indirection
T* operator->() const { ... return pointee_; }
Module Summary
private:
T* pointee_; // Holding the pointee
};
Programming in Modern C++ Partha Pratim Das M57.9
The Smartness Charter (Recap Module 56)

Module M57

• It always points either to a valid allocated object or is NULL

L
Partha Pratim
Das
• It deletes the object once there are no more references to it

E
Objectives &
Outlines • Fast: Preferably zero de-referencing and minimal manipulation overhead

T
Smart Pointers
Recap • Raw pointers to be only explicitly converted into smart pointers. Easy search using grep
Ownership Policy
is needed (it is unsafe)

P
Conversion Policy
Null-test Policy
• It can be used with existing code

N
Resource
Management • Programs that do not do low-level stuff can be written exclusively using this pointer.
std::unique ptr
std::shared ptr No Raw pointers needed
std::weak ptr
std::auto ptr • Thread-safe
Summary
Binary Tree
• Exception safe
Recommendations

Module Summary
• It should not have problems with circular references
• Programmers would not keep raw pointers and smart pointers to the same object

Programming in Modern C++ Partha Pratim Das M57.10


Policies (Recap Module 56)

Module M57

• The charter is managed through a set of policies that bring in flexibility and leads to

L
Partha Pratim
Das
different flavors of smart pointers

E
Objectives &
Outlines • Major policies include:

T
Smart Pointers ◦ Storage Policy
Recap
Ownership Policy ◦ Ownership Policy

P
Conversion Policy
Null-test Policy
◦ Conversion Policy
◦ Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.11


Ownership Policy: Exclusive and Shared (Recap Module 56)

Module M57 Exclusive Ownership Shared Ownership

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
• Exclusive Ownership Policy • Shared Ownership Policy
Summary • Transfer ownership on copy • Multiple Smart pointers to same pointee
Binary Tree • On Copy: Source is set to NULL • On Copy: Reference Count (RC) incremented
Recommendations • On Delete: Destroy the pointee Object • On Delete: RC decremented, if RC > 0.
Module Summary Pointee object destroyed for RC = 0
• std::auto ptr (C++03), std::unique ptr • std::shared ptr, std::weak ptr (C++11)
(C++11)
• Coded in: C-Ctor, operator= • Coded in: Ctor, C-Ctor, operator=, Dtor
Programming in Modern C++ Partha Pratim Das M57.12
Ownership Policy: Exclusive and Shared (Recap Module 56)

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Extra indirection & non-intrusive counter
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management Extra pointer &
std::unique ptr non-intrusive counter Reference linking
std::shared ptr
std::weak ptr
std::auto ptr Intrusive counter
Summary • Non-Intrusive Counter • Non-Intrusive Counter • Reference Linking
Binary Tree ◦ Addl. count ptr per ◦ Addl. count ptr removed ◦ Overhead of two addl. ptrs
Recommendations smart ptr ◦ But addl. access level means slower speed ◦ Doubly-linked list for constant
◦ Count in Free Store • Intrusive Counter time:
Module Summary
◦ Allocation of Count . For Append, Remove &
may be slow as it is too ◦ Most optimized RC smart ptr
small (may be improved ◦ Cannot work for an already existing design Empty detection
by global pool) ◦ Used in Component Object Model (COM)
Programming in Modern C++ Partha Pratim Das M57.13
Smart Pointers: Ownership Policy

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree Smart Pointers: Ownership Policy
Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.14


Ownership Policy: Reference Management: Shortcoming

Module M57

• Circular / Cyclic Reference

L
Partha Pratim
Das
◦ Object A holds a smart pointer to an object B. Object B holds a smart pointer to

E
Objectives &
Outlines A. Forms a cyclic reference

T
Smart Pointers . Typical for a Tree: Child & Parent pointers
Recap
Ownership Policy ◦ Cyclic references go undetected

P
Conversion Policy
Null-test Policy . Both the two objects remain allocated forever

N
Resource
Management
. Resource Leak occurs
std::unique ptr ◦ The cycles can span multiple objects
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.15


Ownership Policy: Cyclic Reference: Hack

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree

Recommendations

Module Summary

• Use Smart pointer (std::shared ptr) from Parent to Child: Data Structure Pointers
• Use Weak pointer (std::weak ptr) from Child to Parent: Algorithm Pointers
Programming in Modern C++ Partha Pratim Das M57.16
Ownership Policy: Cyclic Reference: Solution

Module M57

• Maintain two flavors of RC Smart Pointers

L
Partha Pratim
Das
◦ Strong pointers that really link up the data structure (Child / Sibling Links). They

E
Objectives &
Outlines behave like regular RC. std::shared ptr

T
Smart Pointers . These are Ownership pointers
Recap
Ownership Policy ◦ Weak pointer for cross / back references in the data structure (Parent / Reverse

P
Conversion Policy
Null-test Policy
Sibling Links). std::weak ptr

N
Resource
Management
. These are Observer pointers
std::unique ptr
std::shared ptr
• Keep two reference counts:
std::weak ptr
std::auto ptr
◦ One for strong pointers, and
Summary ◦ One for weak pointers
Binary Tree

Recommendations • While dereferencing a weak pointer, check the strong reference count:
Module Summary ◦ If it is zero, return NULL. As if, the object is gone

Programming in Modern C++ Partha Pratim Das M57.17


Smart Pointers: Conversion Policy

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree Smart Pointers: Conversion Policy
Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.18


Implicit Conversion Policy

Module M57 • Consider

L
Partha Pratim
Das
void Fun(Something* p); ... // For maximum compatibility this should work
SmartPtr<Something> sp(new Something);

E
Objectives &
Outlines Fun(sp); // OK or error?

T
Smart Pointers
Recap
Ownership Policy
• User-Defined Conversion (cast)

P
Conversion Policy
Null-test Policy
template<typename T>class SmartPtr { public:

N
Resource
Management
operator T*() { return pointee_; } // user-defined conversion to T*
std::unique ptr };
std::shared ptr
std::weak ptr • Pitfall: This following compiles okay and defeats the purpose of the smart pointer
std::auto ptr
Summary
Binary Tree SmartPtr<Something> sp; ... // Undetected semantic error at compile time
Recommendations
delete sp; // Compiler passes this by casting to raw pointer
Module Summary
• No conversion allowed in library. No operator T*() const noexcept; is even provided.
Use get() to obtain the raw pointer from unique ptr or shared ptr
Programming in Modern C++ Partha Pratim Das M57.19
Smart Pointers: Null-test Policy

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree Smart Pointers: Null-test Policy
Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.20


Null Test Policy

Module M57

• How to check if the smart pointer is null? Expect the following to work?

L
Partha Pratim
Das

E
Objectives & SmartPtr<Something> sp1, sp2;
Outlines
Something* p; ...

T
Smart Pointers
Recap
if (sp1) // Test 1: direct test for non-null pointer ...
Ownership Policy

P
Conversion Policy if (!sp1) // Test 2: direct test for null pointer ...
Null-test Policy if (sp1 == 0) // Test 3: explicit test for null pointer ...

N
Resource
Management
std::unique ptr • Without implicit conversion to to raw pointers, these cannot work
std::shared ptr
std::weak ptr • Overloading bool operator!() { return pointee == 0; } would pass Test 2, would
std::auto ptr
Summary
need Test 1 to be written as if(!!sp), and fail Test 3
Binary Tree
• The library provides explicit operator bool() const noexcept; for the purpose in
Recommendations
unique ptr and shared ptr
Module Summary
• Test 1, Test 2 and Test 3 work

Programming in Modern C++ Partha Pratim Das M57.21


Resource Management

Module M57
Sources:

L
Partha Pratim
Das
Chapter 4. Smart Pointers: Effective Modern C++, Scott Meyers
◦ Item 18: Use std::unique ptr for exclusive-ownership resource management
◦ Item 19: Use std::shared ptr for shared-ownership resource management

E
Objectives &
Outlines ◦ Item 20: Use std::weak ptr for std::shared ptr-like pointers that can dangle
◦ Item 21: Prefer std::make unique and std::make shared to direct use of new

T
Smart Pointers
Recap • Smart Pointer in C++ Standard Library
Ownership Policy
◦ std::unique ptr, cppreference

P
Conversion Policy
Null-test Policy
◦ std::shared ptr, cppreference
◦ std::weak ptr, cppreference

N
Resource
Management
◦ std::auto ptr, cppreference
std::unique ptr • The Rule of The Big Three (and a half) – Resource Management in C++, 2014
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree
Resource Management
Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.22


Resource Management

Module M57

• Smart pointers enable automatic, exception-safe, object lifetime management

L
Partha Pratim
Das
• The various Pointers are:

E
Objectives &
Outlines ◦ unique ptr: smart pointer with unique object ownership semantics

T
Smart Pointers ◦ shared ptr: smart pointer with shared object ownership semantics
Recap
Ownership Policy ◦ weak ptr: weak reference to an object managed by std::shared ptr

P
Conversion Policy
Null-test Policy
◦ auto ptr: smart pointer with strict object ownership semantics

N
Resource
Management
• All these are Defined in header <memory>
std::unique ptr
std::shared ptr
• First three pointers are included in C++11 where as last one is as in C++03
std::weak ptr
std::auto ptr
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.23


Resource Management: std::unique ptr

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree Resource Management: std::unique ptr
Recommendations

Module Summary
Sources:
• std::unique ptr, cppreference

Programming in Modern C++ Partha Pratim Das M57.24


std::unique ptr

Module M57
// Managing a single object. Deleter may be use supplied or default delete
template<typename T, typename Deleter = std::default_delete <T> >

L
Partha Pratim
Das
class unique_ptr;

E
Objectives &
Outlines // Managing an array of object

T
Smart Pointers template<typename T, typename Deleter>
Recap
class unique_ptr<T[], Deleter>;
Ownership Policy

P
Conversion Policy
Null-test Policy
• It retains sole ownership of an object through a pointer and destroys that object when the

N
Resource
Management unique ptr goes out of scope
std::unique ptr
std::shared ptr
• No two unique ptr instances can manage the same object
std::weak ptr • The raw pointer to the managed object can be obtained by get()
std::auto ptr
Summary
• The object is destroyed and its memory deallocated when:
Binary Tree
◦ The managing unique ptr object is destroyed, or
Recommendations
◦ The managing unique ptr object is assigned another pointer via operator= or reset()
Module Summary
• The ownership can also be relinquished by release() which returns the raw pointer of the
managed object

Programming in Modern C++ Partha Pratim Das M57.25


std::unique ptr

Module M57

• The object is destroyed using a potentially user-supplied deleter by calling Deleter(ptr)

L
Partha Pratim
Das
• A unique ptr may alternatively own no object (managed object pointer is nullptr), in which

E
Objectives & case it is called empty
Outlines
• There are two versions of std::unique ptr:

T
Smart Pointers
Recap ◦ Manages the lifetime of a single object (for example, allocated with new)
Ownership Policy
◦ Manages the lifetime of a dynamically-allocated array of objects (for example, allocated

P
Conversion Policy
Null-test Policy with new[])

N
Resource
Management
• Typical uses of std::unique ptr include:
std::unique ptr ◦ exception safety to classes and functions that handle objects with dynamic lifetime, by
std::shared ptr
std::weak ptr guaranteeing deletion
std::auto ptr
Summary
◦ ownership of uniquely-owned objects with dynamic lifetime into functions
Binary Tree ◦ ownership of uniquely-owned objects with dynamic lifetime from functions
Recommendations ◦ element type in move-aware containers, such as std::vector.
Module Summary

Programming in Modern C++ Partha Pratim Das M57.26


std::unique ptr: Example

Module M57 #include <iostream>


#include <memory>

L
Partha Pratim
Das struct Foo {
Foo() { std::cout << "Foo::Foo\n"; }

E
Objectives &
Outlines ~Foo() { std::cout << "Foo::~Foo\n"; }
void bar() { std::cout << "Foo::bar\n"; }

T
Smart Pointers
Recap };
Ownership Policy void f(const Foo &) { std::cout << "f(const Foo&)\n"; }

P
Conversion Policy
Null-test Policy
int main() {
std::unique_ptr<Foo> p1 = std::make_unique<Foo>(); // (C++14) p1 owns Foo. // Foo::Foo

N
Resource
Management // std::unique_ptr<Foo> p1(new Foo); // (C++11) p1 owns Foo. // Foo::Foo
std::unique ptr if (p1) p1->bar(); // Foo::bar
std::shared ptr
std::weak ptr
{
std::auto ptr std::unique_ptr<Foo> p2(std::move(p1)); // now p2 owns Foo
Summary
f(*p2); // f(const Foo&)
Binary Tree
p1 = std::move(p2); // ownership returns to p1
Recommendations
std::cout << "destroying p2...\n"; // destroying p2...
Module Summary }
if (p1) p1->bar(); // Foo instance is destroyed when p1 goes out of scope. // Foo::bar
} // Foo::~Foo
Programming in Modern C++ Partha Pratim Das M57.27
Resource Management: std::shared ptr

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree Resource Management: std::shared ptr
Recommendations

Module Summary
Sources:
• std::shared ptr, cppreference

Programming in Modern C++ Partha Pratim Das M57.28


std::shared ptr

Module M57
template<typename T> class shared ptr;

L
Partha Pratim
Das
• It retains shared ownership of an object through a pointer. Several shared ptr objects may
own the same object

E
Objectives &
Outlines
• Object is destroyed and its memory deallocated when either of the following happens:

T
Smart Pointers
Recap ◦ the last remaining shared ptr owning the object is destroyed
Ownership Policy ◦ the last remaining shared ptr owning the object is assigned another pointer via

P
Conversion Policy
Null-test Policy operator= or reset()

N
Resource • The object is destroyed using delete-expression or a custom deleter that is supplied to
Management
std::unique ptr shared ptr during construction
std::shared ptr
std::weak ptr
• The raw pointer to the managed object can be obtained by get()
std::auto ptr • We can get the number of managed objects by invoking use count()
Summary
Binary Tree
• A shared ptr can share ownership of an object while storing a pointer to another object
Recommendations
• It may also own no objects, in which case it is called empty
Module Summary
• All specializations of shared ptr meet the requirements of CopyConstructible,
CopyAssignable, and LessThanComparable and are contextually convertible to bool

Programming in Modern C++ Partha Pratim Das M57.29


std::shared ptr: Example

Module M57 #include <iostream>


#include <memory> // We need to include this for shared_ptr

L
Partha Pratim
Das using namespace std;
int main() {

E
Objectives & shared_ptr<int> p1 = make_shared<int>(); // Creating through make_shared
Outlines
*p1 = 78; // Set a value for the managed object

T
Smart Pointers
Recap
cout << "p1 = " << *p1 << endl; // Access the value from managed object: p1 = 78
Ownership Policy cout << "p1 RC = " << p1.use_count() << endl; // Show RC: p1 RC = 1

P
Conversion Policy shared_ptr<int> p2(p1); // Second shared_ptr points to same pointer. RC = 2
Null-test Policy
cout << "p2 RC = " << p2.use_count() << endl; // Show RC: p2 RC = 2

N
Resource cout << "p1 RC = " << p1.use_count() << endl; // Show RC: p1 RC = 2
Management
std::unique ptr if (p1 == p2) { cout << "Same objects\n"; } // Compare ptrs: Same object
std::shared ptr cout<< "Reset p1 " << endl; // : Reset p1
std::weak ptr
std::auto ptr
p1.reset(); // Reset the shared_ptr - it will not point to any object
Summary cout << "p1 RC = " << p1.use_count() << endl; // RC = 0: p1 RC = 0
Binary Tree p1.reset(new int(11)); // Reset the shared_ptr with a new Pointer
Recommendations cout << "p1 RC = " << p1.use_count() << endl; // RC = 1: p1 RC = 1
Module Summary p1 = nullptr; // Assign nullptr to de-attach managed object
cout << "p1 RC = " << p1.use_count() << endl; // RC = 0: p1 RC = 0
if (!p1) { cout << "p1 is NULL" << endl; } // Test pointer: p1 is NULL
}
Programming in Modern C++ Partha Pratim Das M57.30
Resource Management: std::weak ptr

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree Resource Management: std::weak ptr
Recommendations

Module Summary
Sources:
• std::weak ptr, cppreference

Programming in Modern C++ Partha Pratim Das M57.31


std::weak ptr

Module M57
template<typename T> class weak ptr;

L
Partha Pratim
Das • It holds a non-owning (weak) reference to an object that is managed by std::shared ptr
• It must be converted to std::shared ptr in order to access the referenced object

E
Objectives &
Outlines
• std::weak ptr models temporary ownership: when an object needs to be accessed only if it

T
Smart Pointers
exists, and it may be deleted at any time by someone else
Recap
Ownership Policy • It is used to track the object, and it is converted to std::shared ptr to assume temporary

P
Conversion Policy
ownership
Null-test Policy
• We can get the number of managed objects by invoking use count()

N
Resource
Management • To check if the managed object is already deleted we can call expired()
std::unique ptr
std::shared ptr
• Also, lock() can be used to creates a shared ptr from a weak ptr to manage the referenced
std::weak ptr object
std::auto ptr
Summary • If the original std::shared ptr is destroyed at this time, the object’s lifetime is extended until
Binary Tree
the temporary std::shared ptr is destroyed as well
Recommendations
• Note: It is used to break circular references of std::shared ptr. It cannot be used to access
Module Summary
the managed object

Programming in Modern C++ Partha Pratim Das M57.32


std::weak ptr: Example

Module M57
#include <iostream>
#include <memory>

L
Partha Pratim
Das

E
Objectives & std::weak_ptr<int> gw;
Outlines

T
Smart Pointers void f() {
Recap
if (auto spt = gw.lock()) { // Has to be copied into a shared_ptr before usage
Ownership Policy

P
Conversion Policy
std::cout << *spt << "\n";
Null-test Policy }

N
Resource else { std::cout << "gw is expired\n"; }
Management }
std::unique ptr
std::shared ptr
int main() {
std::weak ptr {
std::auto ptr auto sp = std::make_shared<int>(42); //
Summary
Binary Tree
gw = sp;
Recommendations
f(); // 42
}
Module Summary
f(); // gw is expired
}

Programming in Modern C++ Partha Pratim Das M57.33


Resource Management: std::auto ptr

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree Resource Management: std::auto ptr
Recommendations

Module Summary
Sources:
• std::auto ptr, cppreference

Programming in Modern C++ Partha Pratim Das M57.34


std::auto ptr

Module M57
// Managing a single object in C++03. Deprecated in C++11, removed in C++17
template<typename T> class auto_ptr;

L
Partha Pratim
Das

E
Objectives & template<> class auto_ptr<void>;
Outlines

T
Smart Pointers
Recap • It retains sole ownership of an object through a pointer and destroys that object when
Ownership Policy
the auto ptr goes out of scope

P
Conversion Policy
Null-test Policy • No two auto ptr instances can manage the same object

N
Resource
Management
• The raw pointer to the managed object can be obtained by get()
std::unique ptr • The object is destroyed and its memory deallocated when:
std::shared ptr
std::weak ptr ◦ The managing auto ptr object is destroyed, or
std::auto ptr
Summary ◦ The managing auto ptr object is assigned another pointer via operator= or
Binary Tree
reset()
Recommendations

Module Summary
• The ownership can also be relinquished by release() which returns the raw pointer of
the managed object
• Never use auto ptr in C++11 and beyond
Programming in Modern C++ Partha Pratim Das M57.35
Resource Management: Summary of Smart Pointer Operations

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr Resource Management: Summary of Smart Pointer
Summary
Binary Tree
Operations
Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.36


Summary of Smart Pointer Operations

Module M57 Member unique ptr shared ptr weak ptr auto ptr Remarks
operator= Y Y Y Y assigns the ptr1

L
Partha Pratim
Das release Y N N Y returns a ptr to the managed object and
releases the ownership

E
Objectives & reset Y Y Y Y replaces the managed object
Outlines swap Y Y Y N swaps the managed objects

T
Smart Pointers get Y Y N Y returns a ptr to the managed obj
Recap operator bool Y Y N N checks if the stored ptr is not null
Ownership Policy owner before N Y Y N owner-based ordering of smart pointers

P
Conversion Policy operator* Y Y N Y accesses the managed object
Null-test Policy operator-> Y Y N Y accesses the managed object

N
Resource operator[] Y Y (C++17) N N indexed access to the managed array
Management use count N Y Y N returns the number of shared ptr ob-
std::unique ptr jects that manage the object
std::shared ptr
make unique (C++14) unique ptr creates a unique ptr that manages a new object
std::weak ptr
std::auto ptr
make shared shared ptr creates a shared pointer that manages a new object
Summary static pointer cast shared ptr applies static cast to the stored ptr
Binary Tree dynamic pointer cast shared ptr applies dynamic cast to the stored ptr
Recommendations
const pointer cast shared ptr applies const cast to the stored ptr
reinterpret pointer cast shared ptr applies reinterpret cast to the stored ptr (C++17)
Module Summary expired weak ptr checks whether the referenced obj was already deleted
lock weak ptr creates a shared ptr that manages the referenced object

1 transfers ownership from another auto ptr


Programming in Modern C++ Partha Pratim Das M57.37
Resource Management: Binary Tree

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree Resource Management: Binary Tree
Recommendations
Sources:
Module Summary
• std::shared ptr, cppreference
• std::weak ptr, cppreference

Programming in Modern C++ Partha Pratim Das M57.38


Binary Tree

Module M57

• We show an example of a binary tree where every node keep a back pointer to its parent

L
Partha Pratim
Das
• This leads to circularity and using std::shared ptr we cannot clean up the tree

E
Objectives &
Outlines • So we use std::shared ptr for the two children and std::weak ptr

T
Smart Pointers
Recap • Similar strategy may be employed in every case of circular data structure design
Ownership Policy

P
Conversion Policy • Note that using std::shared ptr for a binary tree may be an overkill as every node is
Null-test Policy
held by its unique parent. So using std::unique ptr for child and raw pointer for

N
Resource
Management parent may be more optimal
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.39


Binary Tree using std::shared ptr and std::weak ptr

Module M57 #include <iostream> int main() {


#include <memory> shared_ptr<Node> root = // root: 2

L
Partha Pratim
Das using namespace std; make_shared<Node>(2);
struct Node { root->lc = // left child: 1

E
Objectives &
Outlines shared_ptr<Node> lc; // owns left child make_shared<Node>(1);
shared_ptr<Node> rc; // owns right child root->rc = // right child: 3

T
Smart Pointers
Recap weak_ptr<Node> parent; // observes parent make_shared<Node>(3);
Ownership Policy int v; // Node value root->lc->parent = root; // back link

P
Conversion Policy
Node(int i = 0): v(i) root->rc->parent = root;
Null-test Policy
{ cout << "Node = " << v << endl; }

N
Resource shared_ptr<Node> p = root; // visit tree
Management ~Node()
std::unique ptr { cout << "~Node = " << v << endl; } weak_ptr<Node> q; // hold parent
std::shared ptr }; cout << p->v << ’ ’;
std::weak ptr
std::auto ptr
p = p->lc;
Summary
Node = 2 cout << p->v << ’ ’;
Binary Tree Node = 1 q = p->parent;
Recommendations Node = 3 p = q.lock(); // weak to shared
Module Summary
2 1 3 p = p->rc;
~Node = 2 // Nodes will not be cleaned cout << p->v << ’ ’;
~Node = 3 // if parent is a shared_ptr cout << endl;
~Node = 1 // This is due to circularity }
Programming in Modern C++ Partha Pratim Das M57.40
Recommendations for Smart Pointers

Module M57

L
Partha Pratim
Das

E
Objectives &
Outlines

T
Smart Pointers
Recap
Ownership Policy

P
Conversion Policy
Null-test Policy

N
Resource
Management
std::unique ptr
std::shared ptr
std::weak ptr
std::auto ptr Recommendations for Smart Pointers
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.41


Recommendations for Smart Pointers

Module M57

• Scott Meyers in the his book Effective Modern C++ (Chapter 4. Smart Pointers) has

L
Partha Pratim
Das
made the following recommendations for the use of smart pointers for resource

E
Objectives &
Outlines
management:
◦ Item 18: Use std::unique ptr for exclusive-ownership resource management

T
Smart Pointers
Recap
Ownership Policy
◦ Item 19: Use std::shared ptr for shared-ownership resource management

P
Conversion Policy ◦ Item 20: Use std::weak ptr for std::shared ptr-like pointers that can dangle
Null-test Policy
◦ Item 21: Prefer std::make unique and std::make shared to direct use of new

N
Resource
Management
std::unique ptr
• We strongly recommend the use of these for modern designs
std::shared ptr
std::weak ptr
std::auto ptr
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.42


Module Summary

Module M57

• Discussed various policies of smart pointer

L
Partha Pratim
Das
◦ Ownership Policies

E
Objectives &
Outlines ◦ Implicit Conversion policy
◦ Null test policy

T
Smart Pointers
Recap
Ownership Policy • Familiarized with Resource Management using Smart Pointers from Standard Library

P
Conversion Policy
Null-test Policy ◦ unique ptr

N
Resource ◦ shared ptr
Management
std::unique ptr ◦ weak ptr
std::shared ptr
std::weak ptr
◦ auto ptr
std::auto ptr
Summary
Binary Tree

Recommendations

Module Summary

Programming in Modern C++ Partha Pratim Das M57.43

You might also like