I would like to know if the count of references in shared_ptr becomes 1.
In other words, I want to observe shared_ptr.
It reminds me Observer pattern.
The whole picture is that there are several threads in the application requesting a logger instance. When each thread has done its job it deallocates its instance of shared_ptr. Therefore, once all threads have completed, there is left a single instance of object and just one reference to the object - shared_ptr. And the question is how to get rid of it. Evident solution is been rendered here: garbage collector running every 5 minutes...
CodePudding user response:
Therefore, once all theads have completed, there is left a single instance of object and just one reference to the object - shared_ptr. And the question is how to get rid of it.
Simply don't create the extra shared pointer to the object in the first place.
CodePudding user response:
You can use std::shared_ptr::use_count or std::shared_ptr::unique in C 20:
#include <iostream>
#include <memory>
int main( )
{
auto sptr { std::make_shared<double>( 10.0 ) };
std::cout << "use count == " << sptr.use_count( )
<< " --- is unique? " << std::boolalpha << sptr.unique( ) << std::noboolalpha << '\n';
auto sptr2 { sptr };
std::cout << "use count == " << sptr2.use_count( )
<< " --- is unique? " << std::boolalpha << sptr2.unique( ) << '\n';
}
Sample output:
use count == 1 --- is unique? true
use count == 2 --- is unique? false
