In this code:
#include <iostream>
int main(void)
{
std::string {} = "hi";
return 0;
}
This type of declaration is valid in C++. See in Godbolt.
For information, I tested this program from c++11 to c++20 flags as extended initializers are available from c++11 onwards.
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 '='
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With