When Do We Need Smart Pointers?
There are three typical scenarios when smart pointers are appropriate:Shared ownership of resourcesWhen writing exception-safe codeAvoiding common errors, such as resource leaksShared ownership is the case when two or more objects must use a third object. How (or rather when) should that third object be deallocated? To be sure that the timing of deallocation is right, every object referring to the shared resource would have to know about each other to be able to correctly time the release of that resource. That coupling is not viable from a design or a maintenance point of view. The better approach is for the owners to delegate responsibility for lifetime management to a smart pointer. When no more shared owners exist, the smart pointer can safely free the resource.scoped_ptr, shared_ptr, intrusive_ptr, and weak_ptr. Although the complementary scoped_array and shared_array are sometimes useful, they are not used nearly as frequently, and they are so similar to those covered that it would be too repetitive to cover them at the same level of detail.