pros and cons of smart pointers

前端 未结 10 1912
长情又很酷
长情又很酷 2021-02-05 05:31

I came to know that smart pointer is used for resource management and supports RAII.

But what are the corner cases in which smart pointer doesn\'t seem smart and things

相关标签:
10条回答
  • 2021-02-05 06:00

    Here are a few things

    • There's no definite entity which destroys the object. Often it is desired to know exactly when and how an object is being destroyed
    • Circular dependencies - If they exist you'll have a memory leak. That's usually where weak_ptr come to the rescue.
    0 讨论(0)
  • 2021-02-05 06:02

    There is a problem with reference counting in certain types of data structures that have cycles. There can also be problems with accessing smart pointers from multiple threads, concurrent access to reference counts can cause problems. There's a utility in boost called atomic.hpp that can mitigate this problem.

    0 讨论(0)
  • 2021-02-05 06:03

    I would like to mention performance limitations. Smart pointers usually use atomic operations (such as InterlockedIncrement in Win32 API) for reference counting. These functions are significantly slower than plain integer arithmetic.

    In most cases, this performance penalty is not a problem, just make sure you don't make too many unnecessary copies of the smart pointer object (prefer to pass the smart pointer by reference in function calls).

    0 讨论(0)
  • 2021-02-05 06:10

    Raymond Chen is notoriously ambivalent about smart pointers. There are issues about when the destructor actually runs (please note, the destructor runs at a well-defined time in a well-defined order; it's just that once in a while you'll forget that it's after the last line in your function).

    Also remember that "smart pointer" is a pretty big category. I include std::vector in that category (a std::vector is essentially a smart array).

    0 讨论(0)
  • 2021-02-05 06:11

    The following article is a very interesting paper

    Smart Pointers: Can't Live With 'Em, Can't Live Without 'Em

    0 讨论(0)
  • 2021-02-05 06:15

    This is quite interesting: Smart Pointers.
    It's a sample chapter from "Modern C++ Design" by Andrei Alexandrescu.

    0 讨论(0)
提交回复
热议问题