Writing Smart Pointers
In Chapter 5, we examined the standard smart pointers at our disposal, with emphasis on the most important ones: unique_ptr<T> and shared_ptr<T>. These types are precious and important tools in every contemporary C++ programmer’s toolbox, and using them when appropriate leads to programs that are smaller, faster, and simpler than they would be with most handwritten alternatives.
This book aims to discuss how to manage memory in a C++ program. For that reason, in this chapter, we will write simple versions of both unique_ptr<T> and shared_ptr<T> to show ways in which one could write naïve-yet-workable versions of these types if needed. We strongly recommend that you use the standard versions in practice, not those in this book (at least in production code): standard versions have been thoroughly tested, optimized, and used by a multitude of programmers to good effect. The reason we write “homemade” flavors here...