Owning objects and views
C++ has not been limited to owning pointers since its creation: any object can own resources, and we already mentioned that the simplest way to express exclusive ownership is to create a local variable on the stack. Of course, any of such objects can also be owned by a pointer (unique or shared) and when non-owning access is desired, these objects are commonly accessed through raw pointers or references. However, in C++17 and C++20 a different pattern has emerged, and it is worth exploring.
Resource-owning objects
Every C++ programmer is familiar with resource-owning objects; perhaps the most common one is std::string
– an object that owns a character string. Of course, it also has a lot of specialized member functions for operating on strings, but from the point of view of memory ownership, std::string
is essentially an owning char*
pointer. Similarly, std::vector
is an owning object for an array of objects of arbitrary type.
The most common...