...

/

- Example

- 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 this feature in the example below.

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 an std::weak_ptr ...