c++ - Is calling std::min on an empty initializer list (and explicitly specifying the type) undefined behavior? -


calling std::min() empty initializer list not compile (all question can stated in same way std::max()). code:

#include <iostream> #include <algorithm>  int main() {    std::cout << std::min({}) << "\n";    return 0; } 

with clang gives error:

test.cpp:6:17: error: no matching function call 'min'    std::cout << std::min({}) << "\n";                 ^~~~~~~~ algorithm:2599:1: note:        candidate template ignored: couldn't infer template argument '_tp' min(initializer_list<_tp> __t) 

i can see why case not allowed, because difficult agree on sensible value return in case.

however, technically speaking code not compile because template parameter cannot deduced. if force parameter code compiles crash:

#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 

it seems crash arises because std::min() implemented in terms of std::min_element(), , empty initializer list results dereference of invalid end() iterator.

so piece of code undefined behavior under c++11/c++14 ? std::min() stated not compile when called without explicit template parameters? std::min() specified implemented in terms of std::min_element()?

yes, it's ub. per c++14 (n4140) 25.4.7/4:

template <class t> constexpr t min(initializer_list<t> t); 

...

4 requires: t lessthancomparable , copyconstructible , t.size() > 0.

(emphasis mine)

the same wording present in c++11 well.


Comments

Popular posts from this blog

Android : Making Listview full screen -

javascript - Parse JSON from the body of the POST -

javascript - Chrome Extension: Interacting with iframe embedded within popup -