The standard smart pointers
C++ has a relatively small zoo of smart pointers. Before looking at the set of options provided by the standard, let’s take a moment to show the problem we are trying to solve. Consider the following (deliberately incomplete) program. Do you see anything wrong with it?
class X {
// ...
};
X *f();
void g(X *p);
void h() {
X *p = f();
g(p);
delete p;
} This is code that is legal but not something you want to see in a contemporary program. There’s just so much that can go wrong here, such as the following from a non-exhaustive list of potential problems:
- We don’t know whether
g()will calldelete p, leading to a seconddelete(on a destroyed object!) inh()afterward - We don’t know whether
g()might throw, in which case thedelete p;instruction inh()will never be reached - We don’t know whether
h()should be assumed to own...