#include <iostream>
using namespace std;
class Printer
{
weak_ptr<int> m_Value{};
public:
void SetValue(weak_ptr<int> p)
{
m_Value = p;
}
void Print() const
{
cout << "ref count = " << m_Value.use_count() << endl;
if (m_Value.expired())
{
cout << "resource expired";
return;
}
auto sp = m_Value.lock();
cout << "sp ref count = " << sp.use_count() << endl;
cout << "Value is = " << *sp << endl;
}
};
int main()
{
Printer prn;
int num;
cout << "Enter num = ";
cin >> num;
shared_ptr<int> p{new int(num)};
prn.SetValue(p);
if (*p > 10)
{
p = nullptr;
}
prn.Print();
}
I was learning C++ 11/14/17 concepts and I learned about this weak pointer concept. Above code is the example I learned and implemented and understood it and above code has no bug. But my doubt is on library design for this weak pointer.
auto sp = m_Value.lock();
why this line is left for programmer to call instead of putting inside weak pointer design itself, because whenever the shared pointer shares value to weak pointer ref count has to be incremented automatically right? what's the corner case that doesn't require this line to be called and so ref count shouldn't be increased.