views:

782

answers:

10

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 ?

+1  A: 

The following article is a very interesting paper

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

Nadir SOUALEM
+7  A: 

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.

sharptooth
*Strong* smart pointers in loops will cause memory to leak, but careful use of *weak* pointers (a part of any complete smart pointer library) allow you to effectively use smart pointers without leaks even with circular structures.
280Z28
this is also related to a common leak with GC, when you have a circular structure and no longer need part of it you have to manually break the cycle to allow GC (or allow GC to collect the whole structure) e.g. c# events
jk
@jk: Not quite the same thing. A GC can handle the case where A points to B and B points to A assuming no other object points to either object. You only have to "break the cycle" if there is still another reference to either A or B. So it's really not the cycle that's the problem. A half decent GC can handle those. The problem is when you create references from rarely used data to long-lived data, without realizing it (as in events). It has nothing to do with cycles.
jalf
+1  A: 

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.
shoosh
Usually it's sufficient to know that an object was destroyed, at more or less the appropriate time. I haven't run into many cases where I needed to know exactly when and in response to what.
David Thornley
The destruction of the object is guaranteed to take place in a well-defined place (even in the case of ref-counted smart pointers the destruction is guaranteed to occur at a well-defined place; it's just that with ref-counted smart pointers you don't know that place until runtime).
Max Lybbert
+5  A: 

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

Dana
A: 

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

Max Lybbert
No, std::vector is no smart array. copying a vector duplicates the array !!!
Benoît
it does manage its own memory though
jk
But something that "manages its own memory is just a "sane C++ class" and *nothing* more. It's the very least you should expect from *any* class. A smart pointer is one which manages *other peoples memory*. One which is given a pointer, and takes care of deleting it at the right time. And the destructor thing is nothing to do with smart pointers. It's a general thing in C++, and any C++ programmer had better know it by heart.
jalf
(1) Bjarne Stroustrup doesn't use the term "smart pointer" but he does note an equivalence in his FAQ: http://www2.research.att.com/~bs/bs_faq2.html#auto_ptr . (2) "Smart pointer" doesn't say anything about copy semantics. std::auto_ptr handles copy very differently from copying a normal pointer, but it's still a (very unpopular) smart pointer. (3) "Smart pointer" doesn't say anything about ownership either; compare shared pointers, weak pointers, and auto_ptr/scoped_ptr.
Max Lybbert
+2  A: 

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.

Benoît
+5  A: 

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

Miroslav Bajtoš
Unless performance penalty becomes obvious, i'd advise against using references to smart pointers. When used as function arguments, it has no negative impact, but it may when used as class members. Beware !
Benoît
@Benoit: I'm pretty sure "pass the smart pointer by reference" specifically means in calls, in which case you really shouldn't advise someone to pass it by value.
280Z28
Yes, I meant passing it as an argument to a function. I have edited the reply to make it more clear.
Miroslav Bajtoš
It's also worth noting passing around raw pointers and failing to failing to use InterlockedIncrement or some other synchronization mechanism in a multithreaded application is unsafe. Given those constraints, in that context, ILCX is much faster than a lock, and much harder to get right. IMHO, this is a pro of smart pointers rather than a con
Andrew Walker
It was already clear when i commented on this answer. But it is difficult for unexperienced programmers to apply one rule for function arguments and another for class members. Hence my first comment. Since it's most of the time pointless to make that distinction, just don't until you find out that you need to.
Benoît
To be fair, shared pointers aren't the only kind of smart pointer. Other types of smart pointers avoid this performance penalty.
jalf
I've made VERY good use of scoped_ptr and a scoped_ptr<FILE> specialization. Very handy for writing check-and-throw/return code.
KitsuneYMG
+1  A: 

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.

James Thompson
+1  A: 

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

Niklas
+4  A: 

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.

peterchen