#include <iostream>
#include <memory>
int main()
{
// create a sharable allocation
std::shared_ptr<int> var1 = std::make_shared<int>(102);
std::cout << "*var1 = " << *var1 << '\n';
// create a weak pointer to our shared pointer. we can't do much with
// it until we convert it to a shared pointer
std::weak_ptr<int> var2 = var1;
try
{ // try shared pointer conversion
std::shared_ptr<int> varx(var2);
std::cout << "*var2 = " << *varx << '\n';
}
catch(std::exception const& ex)
{
std::cout << "Exception: " << ex.what() << '\n';
}
// release original shared pointer. this will release
// the only hard reference to the data, and all weak
// pointers become invalid.
var1.reset();
try
{ // try that again, but this time it should not work
std::shared_ptr<int> varx(var2);
std::cout << "*var2 = " << *varx << '\n';
}
catch(std::exception const& ex)
{
std::cout << "Exception: " << ex.what() << '\n';
}
}