The origins of smart pointers
Raw pointers have many uses in C:
- As a cheap, non-copying view of an object owned by the caller
- As a way for the callee to modify an object owned by the caller
- As one-half of a pointer/length pair, used for arrays
- As an optional argument (either a valid pointer or null)
- As a way to manage memory on the heap
In C++, we have native references (const Foo&
and Foo&
) to handle the first two bullets; plus, move semantics makes it cheap for a callee to take and pass back a complex object by value in most cases, thus completely avoiding aliasing. In C++17 we can use std::string_view
to address some of the first and third bullet. And we've just seen in Chapter 5, Vocabulary Types, that passing an optional<T>
--or perhaps getting fancy with an optional<reference_wrapper<T>>
--is sufficient to handle the fourth bullet.
This chapter will be concerned with the fifth bullet.
Heap allocation comes with a host of problems in C, and all those problems (and more...