Learn C++ Online

Introduction to unique and shared pointers

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

std::unique_ptr

std::shared_ptr

std::make_unique and std::make_shared

Questions

Q1

QIntroduction to unique and shared pointers, Q1

This question is ungraded.

When initializing smart pointers, we move away from the direct use of new and instead use make functions.   will be used to initialize std::unique_ptr<T> objects. Fill in the blank.

Q2

QIntroduction to unique and shared pointers, Q2

This question is ungraded.

std::shared_ptr is used for shared-ownership resource management. Given the following function definition:

template <typename T>
void Foo(std::shared_ptr<T> sp) {
  std::cout << sp.use_count() << std::endl;
}

What will Foo have written to standard output after the following statements have executed?

auto m1 = std::make_shared<int>(7);
Foo(m1);

Note: a shared_ptr's use_count returns the number (i.e., count) of shared_ptr objects engaged shared ownership of the resource pointed to.

Q3

QIntroduction to unique and shared pointers, Q3

This question is ungraded.

The implementation of an std::unique_ptr pointer and essence of this data structure relies on which of the following design patterns / programming idioms?