pros and cons of smart pointers

2019-03-17 14:22发布

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 to be kept in mind while using it ?

10条回答
我只想做你的唯一
2楼-- · 2019-03-17 15:00

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.

查看更多
唯我独甜
3楼-- · 2019-03-17 15:00

The following article is a very interesting paper

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

查看更多
该账号已被封号
4楼-- · 2019-03-17 15:02

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

查看更多
叼着烟拽天下
5楼-- · 2019-03-17 15:07

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

查看更多
Animai°情兽
6楼-- · 2019-03-17 15:08

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.

查看更多
对你真心纯属浪费
7楼-- · 2019-03-17 15:13

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

查看更多
登录 后发表回答