为什么不对initializer_list中的值进行类型检查?

Lud*_*hel 5 c++ g++ std initializer-list list-initialization

如何在没有任何警告或错误的情况下进行编译和运行?我不明白如何将current的int 取消引用值分配给字符串,a而不会出现任何问题。

class Test {
public:
  string a;

  Test(initializer_list<int> t) {
    auto current = t.begin();

    // I am assigning an int to a string!
    a = *current;
  }
};

int main() {
  Test test{65};
  printf("%s\n", test.a.c_str());
}
Run Code Online (Sandbox Code Playgroud)

打印的字符串是

A
Run Code Online (Sandbox Code Playgroud)

相反,此非常相似的代码会产生编译时错误:

int main() {
  initializer_list<int> test1{65};
  auto current = test1.begin();
  string b = *current;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误是:

error: no viable conversion from 'const int' to 'std::__1::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
  string b = *current;
Run Code Online (Sandbox Code Playgroud)

son*_*yao 4

请注意a = *current;string b = *current;执行不同的操作。

a = *current;是一个赋值,它导致调用operator=,并且std::string::operator=有一个重载 take char,这使得a = *current;工作(在从to隐式转换之后)。intchar

4) 用字符 ch 替换内容,就像用assign(std::addressof(ch), 1)

string b = *current;是一个初始化,它尝试调用构造函数std::string来初始化b。但是这些构造函数没有这样的重载int(或char),那么就string b = *current;不起作用。