- Example
As compared to the std::shared_ptr, std::weak_ptr does not change the reference counter of the shared variable. Let's take a look at that feature in the example below.
We'll cover the following...
Example
Press + to interact
// weakPtr.cpp#include <iostream>#include <memory>int main(){std::cout << std::boolalpha << std::endl;auto sharedPtr=std::make_shared<int>(2011);std::weak_ptr<int> weakPtr(sharedPtr);std::cout << "weakPtr.use_count(): " << weakPtr.use_count() << std::endl;std::cout << "sharedPtr.use_count(): " << sharedPtr.use_count() << std::endl;std::cout << "weakPtr.expired(): " << weakPtr.expired() << std::endl;if( std::shared_ptr<int> sharedPtr1 = weakPtr.lock() ) {std::cout << "*sharedPtr: " << *sharedPtr << std::endl;std::cout << "sharedPtr1.use_count(): " << sharedPtr1.use_count() << std::endl;}else{std::cout << "Don't get the resource!" << std::endl;}weakPtr.reset();if( std::shared_ptr<int> sharedPtr1 = weakPtr.lock() ) {std::cout << "*sharedPtr: " << *sharedPtr << std::endl;std::cout << "sharedPtr1.use_count(): " << sharedPtr1.use_count() << std::endl;}else{std::cout << "Don't get the resource!" << std::endl;}std::cout << std::endl;}
Explanation
-
In line 11, we create a
std::weak_ptr
that borrows the resource from thestd::shared_ptr
. -
The output of the program shows that the reference ...