You are on page 1of 9

SMART POINTERS

C++ TRAINING
C++ OBJECT LIFETIME
• objects created on the stack are destructed when their scope ends
• if FOO has a member variable m_bar, m_bar is destructed when FOO is destructed
1/21/2013 C++ Training - Smart Pointers
STD::SHARED_PTR EXAMPLE 1
void Bar() {
std::shared_ptr<int> spc(new int(5));
Foo(spc); // Both spc and spcParam own the memory while in Foo()
// Now only spc owns the memory

// After Bar completes, spc is destroyed, decrementing the ref count and cleaning up the int itself
}

void Foo(std::shared_ptr<int> spcParam) {
// spcParam is another shared_ptr pointing to the same int. After this function completes, spcParam is destroyed and
// the ref count on the object is decremented.
}
1/21/2013 C++ Training - Smart Pointers
STD::SHARED_PTR
• standardized in C++11 STL, platform-neutral
• ref-counted
• access members as you normally would, with ->
• be careful of circular references! use std::weak_ptr where needed
• dangerous to access object outside of std::shared_ptr/std::weak_ptr
1/21/2013 C++ Training - Smart Pointers
STD::SHARED_PTR EXAMPLE 2
std::shared_ptr<int> spc1(new int(5));
std::weak_ptr<int> wpc1 = spc1; // spc1 owns the memory.
{
std::shared_ptr<int> spc2 = wpc1.lock(); // Now spc1 and spc2 own the memory.
if(spc2) // Always check to see if the memory still exists
{
// Do something with spc2
}
} // spc2 is destroyed. Memory is owned by spc1.
spc1.reset(); // Memory is deleted.
std::shared_ptr<int> spc3 = wpc1.lock(); // Memory is gone, so we get an empty shared_ptr.

1/21/2013 C++ Training - Smart Pointers
^ (HAT)
• handle to a Windows Runtime object that internally implements IInspectable
• create such an object using ref new
• ref-counted
• access members as you normally would, with ->
• be careful of circular references! use WeakReference where needed
1/21/2013 C++ Training - Smart Pointers
^ EXAMPLE
Foo::Foo()
{
m_Page = ref new Page(); // Foo has a reference to m_Page
WeakReference wrf(this); // m_Page will have a reference to this Foo so create a weak reference to this
m_Page->DoubleTapped += ref new Windows::Ui::Xaml::Input:: DoubleTappedEventHandler(
[wrf](Object^ sender, Windows::Ui::Xaml::Input::DoubleTappedRoutedEventArgs^ args)
{
Foo^ foo = wrf.Resolve<Foo>(); // Use the weak reference to get the object
if (foo != nullptr) foo->m_eventFired = true;
else throw ref new Platform::DisconnectedException(); // Inform the event that this handler should be removed from the subscriber list
});
}
1/21/2013 C++ Training - Smart Pointers
MORE INFO
std::shared_ptr
• MSDN how-to: http://msdn.microsoft.com/en-us/library/hh279669.aspx

C++/CX
• Type system reference: http://msdn.microsoft.com/en-us/library/windows/apps/br212455.aspx
• Weak references: http://msdn.microsoft.com/en-us/library/windows/apps/hh699859.aspx
1/21/2013 C++ Training - Smart Pointers
QUESTIONS?

1/21/2013 C++ Training - Smart Pointers