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
{
public:
    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
    pLarge->DoSomething();

    // Pass a reference to a method.
    ProcessLargeObject(*pLarge);

} //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

https://msdn.microsoft.com/en-us/library/hh279669.aspx

References

https://msdn.microsoft.com/en-us/library/hh279674.aspx?f=255&MSPPError=-2147217396

https://mbevin.wordpress.com/2012/11/18/smart-pointers/

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s