为什么这个 std::string C++ 代码没有给出编译时错误?

Why doesn't this std::string C++ code give compile-time error?

我有以下片段:

#include <string>

int main(int argc, char *argv[])
{
    std::string a, b, c;
    a + b = c;
    return 0;
}

为什么这段 C++ 代码没有给出编译时错误?这可能是因为 std::string::operator+ 的实施方式,但我的问题是:为什么以这种方式实施?在什么情况下需要这样的行为?

您可以分配给临时对象。没有规则阻止这种情况。

如果您不想临时调用成员函数(在 r-value 上,更一般地说),您可以使用 ref-qualifier在函数声明中。

但是如您所见herestd::string::operator= 没有 ref-qualified 版本。

我不认为标准委员会允许这种行为有明确的目标;我想这个选择背后的基本原理是向程序员强加尽可能少的规则,让他找到有用的应用程序,如果有的话。