Learn C++ Online

Introduction to weak pointers

On this page
This lesson contains approximately 5 minutes of video content.

std::weak_ptr

Questions

Q1

QWeak pointers, Q1

This question is ungraded.

A(n)   is a smart pointer that holds a non-owning reference to a resource managed by a shared pointer.

Q2

QWeak pointers, Q2

This question is ungraded.

A std::weak_ptr models temporary ownership. One must convert a weak pointer to a(n)   to access the referenced object.

Q3

QWeak pointers, Q3

This question is ungraded.

You've implemented a directed graph structured as a collection of nodes using shared pointers. For example, consider the following Node type definition:

struct Node {
  Node(char c) : id(c) {}
  char id;
  std::shared_ptr<Node> ptr;
};

If we invoke CreateCyclicGraph, defined as follows:

void CreateCyclicGraph() {

  auto A = std::make_shared<Node>('A');
  auto B = std::make_shared<Node>('B');
  auto C = std::make_shared<Node>('C');

  A->ptr = B;
  B->ptr = C;
  C->ptr = A;

}

Given the graph's structure and our use of shared pointers:

Q4

QWeak pointers, Q4

This question is ungraded.

Given a reference cycle of shared pointers with no outside pointers pointing into the cycle, memory is leaked since the reference counts cannot reach zero. The best way to prevent this "non-breaking" cycle of std::shared_ptrs is to:

Q5

QWeak pointers, Q5

This question is ungraded.

We prefer (and taught you) to implement a doubly linked list with smart pointers using one owner per node: a doubly linked list implementation using smart pointers should leverage std::unique_ptrs and raw pointers.

However, if you wanted to break from best practice and implement a doubly linked list using shared pointers, each node object in the sequence should have its next and previous node pointers typed (select the best response):