Chapter 4. Smart Pointers
Poets and songwriters have a thing about love. And sometimes about counting. Occasionally both. Inspired by the rather different takes on love and counting by Elizabeth Barrett Browning (“How do I love thee? Let me count the ways.”) and Paul Simon (“There must be 50 ways to leave your lover.”), we might try to enumerate the reasons why a raw pointer is hard to love:
-
Its declaration doesn’t indicate whether it points to a single object or to an array.
-
Its declaration reveals nothing about whether you should destroy what it points to when you’re done using it, i.e., if the pointer owns the thing it points to.
-
If you determine that you should destroy what the pointer points to, there’s no way to tell how. Should you use
delete, or is there a different destruction mechanism (e.g., a dedicated destruction function the pointer should be passed to)? -
If you manage to find out that
deleteis the way to go, Reason 1 means it may not be possible to know whether to use the single-object form (“delete”) or the array form (“delete[]”). If you use the wrong form, results are undefined. -
Assuming you ascertain that the pointer owns what it points to and you discover how to destroy it, it’s difficult to ensure that you perform the destruction exactly once along every path in your code (including those due to exceptions). Missing a path leads to resource leaks, and doing the destruction more than once leads to undefined behavior.
-
There’s typically no way to ...