CIS 29 - Notes for Tuesday, 3/16

Announcements and Reminders

  • Assignment 7 is due next Tuesday and is not accepted late
  • Final next Tuesday 1:45 - 3:45 pm.  The final will be held online.

Group Project Presentations

1:30 pm Group 3
2:00 pm Group 1


Smart Pointers

  • Used to manage dynamically allocated memory
    • Avoid memory leaks
    • Avoid calling delete on the same pointer twice
  • The auto_ptr type has been deprecated since C++11
Why?  

dynamically allocated memory requires a delete - the user must take responsibility for the release of memory.
automatic variables or stack memory variables - memory is automatically released when the variable goes out of scope.

Solution

Use automatic variables, or "wrap" your dynamically allocated memory in automatic variables.

unique_ptr

A unique_ptr is a class template used to hold a pointer to dynamically allocated memory.
  • Each pointer is unique, not shared, owned by the unique_ptr
  • When the unique_ptr goes out of scope, its owned memory (pointer) is deleted
  • Requires the <memory> header file
  • The make_unique function template requires C++14
Some unique_ptr member functions

operator* - returns a reference to the object owned by the unique_ptr
operator-> - allows access to a member of the object owned by the unique_ptr
get - returns the pointer to the object owned by the unique_ptr
release - releases ownership of the object owned by the unique_ptr, does not release memory (possible leak)
reset - releases memory for the object owned by the unique_ptr.  With argument, may take on new ownership
make_unique - allocates memory for an object and returns a unique_ptr to it
Example 17-1 - unique_ptr

shared_ptr

A shared_ptr is a class template that allows multiple objects to point to the same dynamic memory object.
  • Manages multiple pointers to the same address.
  • Implements reference counting
  • Requires the <memory> header file
Some shared_ptr member functions

operator* - returns a reference to the object owned by the shared_ptr
operator-> - allows access to a member of the object owned by the shared_ptr
get - returns the pointer to the object owned by the shared_ptr
use_count - returns the number of shared_ptr that share ownership of an object
reset - releases ownership of a shared object.  Call destructor if only one share exists
make_shared - allocates memory for an object and returns a shared_ptr to it

Example 17-2 - shared_ptr

Reading assignment: Course Notes in the Shared Pointer section, Example 3 (~Page 331)