pros and cons of smart pointers

前端 未结 10 1913
长情又很酷
长情又很酷 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:18

    Smart pointers don't help against loops in graph-like structures.

    For example, object A holds a smart pointer to object B and object B - back to object A. If you release all pointers to both A and B before disconnection A from B (or B from A) both A and B will hold each other and form a happy memory leak.

    Garbage collection could help against that - it could see that both object are unreachable and free them.

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

    Watch out at the transitions - when assigning between raw and smart pointers. Bad smart pointers - like _com_ptr_t - make it worse by allowing implicit conversions. Most errors happen at the transition.

    Watch out for cycles - as mentioned, you need weak pointers to break the cycles. However, in a complex graph that's not always easy to do.

    Too much choice - most libraries offer different implementations with different advantages / drawbacks. Unfortunately, most of the time these different variants are not compatible, which becomes a probem when mixing libraries. (say, LibA uses LOKI, LibB uses boost). Having to plan ahead for enable_shared_from_this sucks, having to decide naming conventions between intrusive_ptr, shared_ptr and weak_ptr for a bunch of objects sucks.


    For me, the single most e advantage of shared_ptr (or one of similar functionality) is that it is coupled to its destruction policy at creation. Both C++ and Win32 offers so many ways of getting rid of things it's not even funny. Coupling at construction time (without affecting the actual type of the pointer) means I have both policies in one place.

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

    Many people run into problems when using smart pointers mixed with raw pointers (to the same objects). A typical example is when interacting with an API that uses raw pointers.
    For example; in boost::shared_ptr there is a .get() function that returns the raw pointer. Good functionality if used with care, but many people seem to trip on it.
    IMHO it's an example of a "leaky abstraction".

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

    Beside technical limitations (already mentioned : circular dependencies), i'd say that the most important thing about smart pointers is to remember that it's still a workaround to get heap-allocated-objects deleted. Stack allocation is the best option for most cases - along with the use of references - to manage the lifetime of objects.

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