表达式 std::string {} = "..." 是什么意思?

Roh*_*ari 16 c++ string

在此代码中:

#include <iostream>

int main(void)
{
    std::string {} = "hi";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这种类型的声明在 C++ 中有效。参见《Godbolt》

  • 这是什么意思?
  • 它如何有效?

作为信息,我测试了这个程序从c++11c++20标志,因为扩展初始值设定项从以后可用c++11

dfr*_*fri 20

std::string::operator=(const char*)不是 & 限定的,这意味着它允许分配给左值和右值。

有些人认为(1)赋值运算符应该是 & 限定的,以禁止对右值赋值:

(1) 例如,旨在用于安全关键 C++ 开发的高完整性 C++ 标准,特别是规则12.5.7 使用引用限定符 & 声明赋值运算符

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

int main() {
    S {} = {};  // error: no viable overloaded '='
}
Run Code Online (Sandbox Code Playgroud)

或者,更明确地说:

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

int main() {
    S {} = {};  // error: overload resolution selected deleted operator '='
}
Run Code Online (Sandbox Code Playgroud)