12

This should be trivial but I can't seem to find it (unless no such class exists!)

What's the STL class (or set of classes) for smart pointers?

UPDATE

Thanks for the responses,
I must say I'm surprised there's no standard implementation.

I ended up using this one: http://archive.gamedev.net/reference/articles/article1060.asp

René Hoffmann
  • 2,766
  • 2
  • 20
  • 43
hasen
  • 161,647
  • 65
  • 194
  • 231

5 Answers5

14

With the exception of the already mentionned TR1 shared_ptr, there is no reference-counted pointer in STL.

I suggest you use boost::shared_ptr (downloading boost will be enough, there is nothing to compile, its implementation is header-only).

You may also want to have a look at smart pointers from Loki libraries (again, header-only implementation).

For an overview of available smart pointers, see there.

Benoît
  • 16,798
  • 8
  • 46
  • 66
  • 3
    boost::shared_ptr was the inspiration for std::tr1::shared_ptr. Subsequently std::tr1::shared_ptr becomes std::shared_ptr in C++0x. – Howard Hinnant Feb 02 '11 at 03:10
9

If you don't want/can't use Boost and your compiler implements TR1, you can use shared_ptr (borrowed from Boost):

#include <tr1/memory>

...

std::tr1::shared_ptr<Foo> ptr(new Foo);

Otherwise, no, there are no smart pointers except std::auto_ptr in vanilla STL.

Alex B
  • 82,554
  • 44
  • 203
  • 280
3

Time marches on, in C++11:

std::shared_ptr
std::weak_ptr

etc.

Dirk Bester
  • 1,791
  • 19
  • 21
1

For COM objects, use CComPtr<>.

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
0

There is an alternative implemented for some time in STL PLUS, see at source forge

"STLplus was originally intended as a library to extend the STL by providing missing container data structures such as smart-pointers, matrices, trees and graphs."

lsalamon
  • 7,998
  • 6
  • 50
  • 63