Smart Pointer Notes

Here is a note on using Smart Pointers for C++

The general idea for smart pointer is creating a wrapper class around raw pointers on stack. This way, when the pointer goes out of scope, the smart pointer, which is released automatically with the destruction of the stack, would invoke the “delete” of the raw pointer. As a result, the raw pointer would be freed when its scope is freed.

This example for msdn doc is a good illustration of the general purpose of smart pointers.

void UseRawPointer()
    // Using a raw pointer -- not recommended.
    Song* pSong = new Song(L"Nothing on You", L"Bruno Mars"); 

    // Use pSong...

    // Don't forget to delete!
    delete pSong;   

void UseSmartPointer()
    // Declare a smart pointer on stack and pass it the raw pointer.
    unique_ptr<Song> song2(new Song(L"Nothing on You", L"Bruno Mars"));

    // Use song2...
    wstring s = song2->duration_;

} // song2 is deleted automatically here.


The smart pointer can be used just as a regular raw pointer, as this example show that

  1. ” ->m” ethod operator still works,
  2. the pointer can be still passes as an argument
class LargeObject
    void DoSomething(){}

void ProcessLargeObject(const LargeObject& lo){}
void SmartPointerDemo()
    // Create the object and pass it to a smart pointer
    std::unique_ptr<LargeObject> pLarge(new LargeObject());

    //Call a method on the object

    // Pass a reference to a method.

} //pLarge is deleted automatically when function block goes out of scope.


There are three types of shared pointers,

  1. unique pointers
  2. shared pointers
  3. weak pointers


The various kinds of smart pointers are used to define “ownership”. Unique pointer is most suitable for cases where there is a single owner. Shared pointer is good for the cases that there will be multiple owners.

Shared pointers


This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s