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?
CodePudding user response:
auto p = w.lock()
is not an assignment. It's a declaration of a variable. You can declare a variable in the condition of an if
statement, but you cannot declare variables within a conditional expression.
You can write:
auto p = w.lock();
std::cout << (
p ? *p
: "Empty"
);
CodePudding user response:
If you want to introduce a variable for an expression (like let
in Lisp or Haskell), you can use a lambda:
std::cout << [p = w.lock()] {return p ? *p : "Empty";}();
This also confines the ?:
, which interprets std::cout
as part of the condition in your question.