C++98 does not provide any smart pointers except auto_ptr
which is fraught with its own issues. C++0X tries to fix this by bringing in a few more varieties (shared_ptr
, unique_ptr
etc.). In the meantime the best bet is to use Boost. Take a look at the various flavors available to you here. Boost is community driven, extensively tested and of course free. There is excellent documentation with sample code that will help you get started.
Can you explain what are the types of smart pointers, how do they work and when to use them?
There are a number of them. In short:
scoped_ptr
<boost/scoped_ptr.hpp>
Simple sole ownership of single
objects. Noncopyable.
scoped_array
<boost/scoped_array.hpp>
Simple sole
ownership of arrays. Noncopyable.
shared_ptr
<boost/shared_ptr.hpp>
Object ownership shared among
multiple pointers.
shared_array
<boost/shared_array.hpp>
Array
ownership shared among multiple
pointers.
weak_ptr
<boost/weak_ptr.hpp>
Non-owning
observers of an object owned by
shared_ptr.
intrusive_ptr
<boost/intrusive_ptr.hpp>
Shared
ownership of objects with an embedded
reference count.
(That is from Boost documentation and note that they have containers for such pointers too!)
Also, what is the "protocol" when receiving or passing raw pointers in interfaces written by other people?
For me the most important rules are:
- Const-qualification
- Not to deallocate stuff I did not allocate
- Check for transfer of ownership/move semantics