What are the equivalent uses of each smart pointer in comparison to similar (but not limited to) some advanced techniques using raw pointers?
My understanding is minimal, but from what I can gather:
- Raw Pointers: Only use if you really, really, really, really, know what you are doing and have carefully hidden usage behind an interface.
- std::auto_ptr: Obsolete never use.
- std::unique_ptr: Singleton pointer that transfers ownership upon assignment.
- std::shared_ptr: Reference counted pointer that does not transfer ownership upon assignment but increments its reference count. When all references leave scope or are explicitly
std::shared_ptr::reset
the underlyingdeallocator
is called. - std::weak_ptr: A sub-type
std::shared_ptr
that does not increment the reference count and is invalidated when its parentstd::shared_ptr
no longer exists. May return and invalid reference. Always check before using.
RAW POINTER EQUIVALENT EXAMPLES
Reference counting, cache implementations: std::map<std::string, std::pair<long, BITMAP*> > _cache;
Singletons with transfer of ownership:
class Keyboard {
public:
//...
static Keyboard* CreateKeyboard();
~Keyboard();
//...
private:
//...
Keyboard();
static Keyboard* _instance;
//...
};
Aggregate Containers, no ownership: Spatial partitioning graphs and trees, iterative containers, etc.
Composite Containers, ownership: Large objects.
--EDIT--
As I am working I came upon an interesting case, DeadMG pointed out that smart pointers are supposed to be used as easy abstractions to take care of resource management; what about file-scope objects that can not be created on the heap at the point of declaration but instead must be created at a later time?
unique_ptr
a Singleton pointer, I suspect you have a totally different meaning of Singleton here. – Certainty...unique_ptr uniquely manages a resource...A resource can be owned by no more than one unique_ptr object; when a unique_ptr object that owns a particular resource is destroyed, the resource is freed. A unique_ptr object may be moved, but not copied...
. Given the remarks, I took this to mean that there can only be one resource in existance. i.e. A Singleton. I may be wrong though, like I said, I have minimal understanding of how smart pointers work and are supposed to be used. – Embouchurestd::shared_ptr
s one-to-many. – Embouchure