gpt4 book ai didi

c++ - 是否在空的初始化程序列表(并明确指定类型)上调用 std::min 未定义的行为?

转载 作者:IT老高 更新时间:2023-10-28 22:26:31 25 4
gpt4 key购买 nike

使用空的初始化列表调用 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++14 (n4140) 25.4.7/4:

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

...

4 Requires: T is LessThanComparable and CopyConstructible and t.size() > 0.

(强调我的)

相同的措辞也出现在 C++11 中。

关于c++ - 是否在空的初始化程序列表(并明确指定类型)上调用 std::min 未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31179878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com