Thursday, April 14, 2011

STL class for reference-counted pointers?

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://www.gamedev.net/reference/articles/article1060.asp

From stackoverflow
  • 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.

  • For COM objects, use CComPtr<>.

    John Dibling : CComPtr isn't reference counted -- the underlying object itself is.
    jeffamaphone : Indeed, that is the case.
  • 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.

0 comments:

Post a Comment