rayimag
rayimag

Reputation: 893

Usage guidelines: shared versus normal pointers

Is there a rigid guideline as to when one should preferably use boost::shared_ptr over normal pointer(T*) and vice-versa?

Upvotes: 1

Views: 319

Answers (3)

Loki Astari
Loki Astari

Reputation: 264401

Unless you are building a smart pointer (don't) then you should probably not be using a RAW pointer (That way leads to madness).

There are a set of smart pointers for different situations:
std::auto_ptr:
std::tr1::shared_ptr AKA (boost::shared_ptr)
boost::scoped_ptr
boost::weak_ptr

Smart Pointers: Or who owns you baby?

The only reason for passing a pointer is to pass a reference to an object that could potentially be NULL (otherwise use a reference) ie you are NOT passing ownership just the use of the object (and if you are passing NULL maybe you should look at the code and ask why).

The std containers don't handle references well so you can put pointers to objects owned by somebody else in a standard container (see Using abstract class as a template type)

Upvotes: 1

John Calsbeek
John Calsbeek

Reputation: 36497

A simple guideline that nearly eliminates the possibility of memory leaks is: always use a named smart pointer variable to hold the result of new.

boost::shared_ptr documentation

Upvotes: 2

Evan Shaw
Evan Shaw

Reputation: 24547

My general rule is, when memory gets passed around a lot and it's difficult to say what owns that memory, shared pointers should be used. (Note that this may also indicate a poor design, so think about things before you just go to shared pointers.) If you're using shared pointers in one place, you should try to use them everywhere. If you don't you'll have to be very careful about how you pass around pointers to avoid double frees.

If your usage of memory is simple and it's obvious what owns memory, then just use normal pointers.

Typically the bigger your project is, the more benefit you'll get out of shared pointers. There aren't rigid rules about this and there shouldn't be. As with many development decisions, there are trade offs and you have to do what's best for you.

Upvotes: 2

Related Questions