When using std::weak_ptr
, it is best practice to access the corresponding std::shared_ptr
with the lock()
method, as so:
std::weak_ptr<std::string> w;
std::shared_ptr<std::string> s = std::make_shared<std::string>("test");
w = s;
if (auto p = w.lock())
std::cout << *p << "\n";
else
std::cout << "Empty";
If I wanted to use the ternary operator to short hand this, it would seem that this:
std::cout << (auto p = w.lock()) ? *p : "Empty";
would be valid code, but this does not compile.
Is it possible to use this approach with the ternary operator?