Home > Software engineering >  What does the expression std::string {} = "..." mean?
What does the expression std::string {} = "..." mean?

Time:11-26

In this code:

#include <iostream>

int main(void)
{
    std::string {} = "hi";
    return 0;
}

This type of declaration is valid in C . See in Godbolt.

  • What does it mean?
  • How is it valid?

For information, I tested this program from c 11 to c 20 flags as extended initializers are available from c 11 onwards.

CodePudding user response:

std::string::operator=(const char*) is not &-qualified, meaning it allows assignment to lvalues as well as rvalues.

Some argue(1) that assignment operators should be &-qualified to ban assignment to rvalues:

(1) E.g. the High Integrity C standard intended for safety-critical C development, particularly rule 12.5.7 Declare assignment operators with the ref-qualifier &.

struct S {
    S& operator=(const S&) & { return *this; }
};

int main() {
    S {} = {};  // error: no viable overloaded '='
}

Or, more explicitly:

struct S {
    S& operator=(const S&) & { return *this; }
    S& operator=(const S&) && = delete;
};

int main() {
    S {} = {};  // error: overload resolution selected deleted operator '='
}
  • Related