Smart Pointers

Fundamentals on Computing for Robotics, Graphics and Computer Vision

Darío Suárez - Adolfo Muñoz

Dynamic Memory Issues

  • Each new always requires a matching delete
  • Possible Issues:
    1. Access an unitilized pointer
    2. Memory leaks: unreachable objects in the heap
    3. Dangling pointers: pointers to already released objects
    4. Multiple deletion: calling delete several times for the same object

Possible solution

  • How we can automatically guarantee the release of the object?
  • Think in objects in the stack and RAII (resource adquisition is initialization)

detour: C++ scopes

  • Scope: context where an element (variable, object, class, function, ...) is visible
source: https://www.oreilly.com/library/view/practical-c-programming/0596004192/ch09.html

Quiz: What are the scopes within this program

Smart Pointers

  • Ensure that objects are released after the last use; e.g., going out of scope
  • Automatically call delete
  • std::unique_ptr and std::shared_ptr templated classes release the object in their destructors

  • Enable same access as regular pointers: * and ->

Rationale example

source: https://courses.cs.washington.edu/courses/cse333/22wi/lectures/16/16-smartptrs_22wi_ink.pdf

Use of ToyPtr

How many times is called delete?

std::unique_ptr<T>

  • Solution for single ownership of an object through a pointer
  • Dealocates when going out of scope
  • Cannot be copied and can be moved
  • Use std::make_unique to create them

std::shared_ptr<T>

  • Solution for multiple pointers to the same object
  • Internally counts the number of refereces to the object
  • Allocation increases the counter, deallocation reduces the counter. When reaching 0, the object is deallocated
  • Use std::make_shared to create them

To learn more