[英]Why aren't values in initializer_list type-checked?
How does this compile and run without any warnings or errors? 如何在没有任何警告或错误的情况下编译和运行? I don't understand how the dereferenced value of
current
, which is an int, can be assigned to the string a
without any problem. 我不明白如何将
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());
}
The printed string is 打印的字符串是
A
In contrast, this very similar code produces a compile-time error: 相反,这个非常相似的代码会产生编译时错误:
int main() {
initializer_list<int> test1{65};
auto current = test1.begin();
string b = *current;
return 0;
}
The error is: 错误是:
error: no viable conversion from 'const int' to 'std::__1::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
string b = *current;
Note that a = *current;
注意
a = *current;
and string b = *current;
和
string b = *current;
perform different things. 执行不同的事情。
a = *current;
is an assignment, which leads to the invocation of operator=
, and std::string::operator=
has an overloading taking char
, which makes a = *current;
是一个赋值,它导致调用
operator=
,并且std::string::operator=
有一个重载取char
,这使得a = *current;
work (after the implicit conversion from int
to char
). work(在从
int
到char
的隐式转换之后)。
4) Replaces the contents with character ch as if by
assign(std::addressof(ch), 1)
4)用字符ch替换内容,就像
assign(std::addressof(ch), 1)
string b = *current;
is an initialization, which tries to call the constructor of std::string
to initialize b
. 是一个初始化,它试图调用
std::string
的构造函数来初始化b
。 But these constructors don't have such overloading taking int
(or char
), then string b = *current;
但是这些构造函数没有这样的重载采用
int
(或char
),然后string b = *current;
won't work. 不行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.