Search code examples
c++conditional-operator

Assign value in ternary operator


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?


Solution

  • 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"
    );