Search⌘ K

- Example

Explore how to use std::weak_ptr in C++ to manage resources without increasing reference counts. Understand how it helps prevent cyclic references while working alongside std::shared_ptr, ensuring safe and efficient memory usage.

We'll cover the following...

Example #

C++
// 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 ...