Join Bill Weinman for an in-depth discussion in this video Why smart pointers?, part of C++ Smart Pointers.
- [Voiceover] In C++, a smart pointer is a template class that uses operator overloads to provide the functionality of a pointer while providing additional features to support improved memory management and safety. A smart pointer is essentially a wrapper around a standard bare C-language pointer. It's designed to provide these benefits while operating as closely as possible to a standard pointer. To illustrate, consider this function signature. I know that this function returns a pointer.
But, what am I supposed to do with this pointer once I'm done with it? Is it static or is allocated? Should I free the memory? Should I use delete or free? Should I expect that some other function will free the memory? I really have no way of knowing. This is the kind of coding problem that leads to memory leaks. On the other hand, with this function, I know exactly what to do. This function returns a unique pointer. I immediately know a few things about this. I know that this is the only copy of this pointer.
This pointer cannot be copied. I know that I can safely destroy its associated resources by calling reset on the pointer, and I know that I can transfer its ownership by moving it. This function returns a shared pointer. With a shared pointer, I can make copies of the pointer and delete those copies as much as I want to. The resources will automatically and safely be destroyed when all copies of this shared pointer are deleted or go out of scope. The shared pointer class manages resources so I don't have to worry about it.
The smart pointer classes are defined in the memory header so you'll need to include memory in order to use these classes. Smart pointers were introduced in C++11 and there are some improvements in C++14. Smart pointers will work in all modern compilers, including Microsoft Visual C++ and the LLVM clang compiler used on Apple Macs. There are some differences in implementation, which I'll describe as we get to them in this course. Smart pointers are easy to use and very powerful.
Unless you need to support older compilers that don't support smart pointers, there's really no reason not to be using them for most purposes.