Skip to Content
Effective Modern C++
book

Effective Modern C++

by Scott Meyers
November 2014
Intermediate to advanced
336 pages
9h 37m
English
O'Reilly Media, Inc.
Content preview from Effective Modern C++

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:

  1. Its declaration doesn’t indicate whether it points to a single object or to an array.

  2. 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.

  3. 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)?

  4. If you manage to find out that delete is 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.

  5. 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.

  6. There’s typically no way to ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Effective C++, Third Edition

Effective C++, Third Edition

Scott Meyers
Embracing Modern C++ Safely

Embracing Modern C++ Safely

John Lakos, Vittorio Romeo, Rostislav Khlebnikov, Alisdair Meredith
C++ Software Design

C++ Software Design

Klaus Iglberger

Publisher Resources

ISBN: 9781491908419Errata Page