The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science

Programming Languages and Tools:

CS:3210:0001

Lecture/Lab #20

Programming with C++

Smart pointers (cont.): unique_ptr, shared_ptr

Warm up

  • What will be the output of the following program?

void bar( int* ptr ) {
    *(ptr + 2) = 33;
    *(ptr + 4) = 55;
}

int main() {
    int a[10] = { 0, 0, 0, 0, 0, 
                  0, 0, 0, 0, 0 };
    bar( a );
    for ( auto n : a )
        std::cout << n << " ";
    std::cout << std::endl;

    int* b = new int[5]();
    bar( b );
    for ( auto n : b )
        std::cout << n << " ";
    std::cout << std::endl;

    int* c = new int( 42 );
    bar( c );
    std::cout << *c << std::endl;
 }

std::unique_ptr

widget* w = new widget();

// ...

delete w;
auto w = std::make_unique<widget>();

// ...
  • “Owns” the object to which it points
  • The object is destroyed when unique_ptr is destroyed
  • u.release() relinquishes the ownership and sets u value to nullptr
  • Only one unique_ptr at a time can point to a given object. 
  • make_unique<T>(...) function allocates the object of type T on the heap and returns a unique_ptr that owns it
  • u.reset( raw_ptr ) resets existing unique_ptr's value
  • Cannot be copied, but can be moved using std::move

Exercise 1

Fix compilation/run-time problems according to the expressed intent of the code and following modern C++ guidelines

  • Open the exercise template

  • Write your code, press Run to test

  • When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)

  • Click on the corresponding option in the "Lab20 exercises" poll in #general

shared_ptr

  • No specific shared_ptr owns the object.

Shared object ownership

  • All shared_ptrs pointing to a specific object "collaborate" to ensure the object is destructed when it’s no longer needed.
  • When the last shared_ptr pointing to an object stops pointing there, that shared_ptr destroys the object it points to.
widget* w = new widget();
foo( w );

widget* w2 = w;
// ...
if ( no_one_uses )
   delete w;
auto w = std::make_shared<widget>();
foo( w );

auto w2 = w;
// ...

shared_ptr (cont.)

T* ptr

[control block]*

T object

reference count

weak count

other data (custom deleter, etc.)

Control block

  • Twice the size of a raw pointer
  • Reference counter  is dynamically allocated

 Primary characteristics: 

  • Reference counter increments/decrements are atomic
  • Supports custom deleters

shared_ptr<T>

Programming with C++, Fall 2019, Lecture #20

By Aleksey Gurtovoy

Programming with C++, Fall 2019, Lecture #20

Smart pointers (cont.): unique_ptr, shared_ptr

  • 565