Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the expression std::string {} = "..." mean?

Tags:

c++

string

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.

like image 510
Rohan Bari Avatar asked Dec 31 '25 13:12

Rohan Bari


1 Answers

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 '='
}
like image 113
dfrib Avatar answered Jan 03 '26 02:01

dfrib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!