使用空的初始化程序列表调用std::min()通常不会编译(对于std::max(),所有问题都可以用相同的方式描述)。此代码:
#include <iostream>
#include <algorithm>
int main() {
std::cout << std::min({}) << "\n";
return 0;
}使用clang提供了以下错误:
test.cpp:6:17: error: no matching function for call to 'min'
std::cout << std::min({}) << "\n";
^~~~~~~~
algorithm:2599:1: note:
candidate template ignored: couldn't infer template argument '_Tp'
min(initializer_list<_Tp> __t)我明白为何不容许这种情况出现,因为在这种情况下,很难就合理的价值达成协议。
但是,从技术上讲,代码并不只是因为无法推断模板参数而编译。如果强制使用参数,代码会编译,但会崩溃:
#include <iostream>
#include <algorithm>
int main() {
std::cout << std::min<int>({}) << "\n";
return 0;
}
$ clang++ -std=c++11 test.cpp -o test
$ ./test
Segmentation fault: 11出现崩溃似乎是因为std::min()是用std::min_element()实现的,空的初始化器列表会导致无效的end()迭代器取消引用。
那么,这段代码是C++11/C++14下未定义的行为吗?std::min()是否声明在没有显式模板参数的情况下调用时不会编译?是否指定std::min()按std::min_element()实现?
发布于 2015-07-02 08:55:39
是的,是UB。根据C++14 (n4140) 25.4.7/4:
模板常数T min(initializer_list t); ..。 4要求:
T是LessThanComparable,CopyConstructible和CopyConstructible
(强调地雷)
同样的措辞也出现在C++11中。
https://stackoverflow.com/questions/31179878
复制相似问题