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?
pinside of the first expression of?:. However, assignments are expressions, so something like(p = w.lock()) ? *p : "Empty"would be valid, assumingpwas already declared.poutside the ternary and then assign it inside, but then you can't use the placeholderauto. It'd bestd::shared_ptr<std::string> p; std::cout << (p = w.lock()) ? *p : "Empty";autoin that case, but you can still deduce theshared_ptrtype from theweak_ptr, by usingstd::shared_ptr<decltype(w)::element_type> p;, or even simplerdecltype(w.lock()) p;