Created
September 27, 2013 12:02
-
-
Save RklAlx/6727565 to your computer and use it in GitHub Desktop.
std::weak_ptr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* A std::shared_ptr uses reference counting, so circular references are potentially a problem. | |
To break up cycles, std::weak_ptr can be used to access the stored object. | |
The stored object will be deleted if the only references to the object are weak_ptr references. | |
weak_ptr therefore does not ensure that the object will continue to exist, but it can ask for the resource. */ | |
std::shared_ptr<int> p1(new int(5)); | |
std::weak_ptr<int> wp1 = p1; //p1 owns the memory. | |
{ | |
std::shared_ptr<int> p2 = wp1.lock(); //Now p1 and p2 own the memory. | |
if(p2) //Always check to see if the memory still exists | |
{ | |
//Do something with p2 | |
} | |
} //p2 is destroyed. Memory is owned by p1. | |
p1.reset(); //Memory is deleted. | |
std::shared_ptr<int> p3 = wp1.lock(); //Memory is gone, so we get an empty shared_ptr. | |
if(p3) | |
{ | |
//Will not execute this. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment