【发布时间】:2015-07-02 08:52:58
【问题描述】:
使用空的初始化列表调用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() 的形式实现?
【问题讨论】:
-
我没想到它会做任何特别的事情。
-
我同意原则上没有好的答案。我什至在问题中说明了这一点。但是由于调用它的一种方式可以编译而另一种不可以,所以我问编译的方式是否确实指定为 UB。
标签: c++ c++11 c++14 undefined-behavior stl-algorithm