Open2
std::minmaxの罠
int main()
{
auto [min1, max1] = std::minmax(2, 1); // UB
auto [min2, max2] = std::minmax({2, 1});
auto [min3, max3] = std::ranges::minmax(2, 1); // UB
auto [min4, max4] = std::ranges::minmax({2, 1});
}
Clang 17.0.1
$ clang++ prog.cc -std=c++2a
prog.cc:6:35: warning: temporary whose address is used as value of local variable '[min1, max1]' will be destroyed at the end of the full-expression [-Wdangling]
6 | auto [min1, max1] = std::minmax(2, 1);
| ^
prog.cc:6:38: warning: temporary whose address is used as value of local variable '[min1, max1]' will be destroyed at the end of the full-expression [-Wdangling]
6 | auto [min1, max1] = std::minmax(2, 1);
| ^
prog.cc:8:43: warning: temporary whose address is used as value of local variable '[min3, max3]' will be destroyed at the end of the full-expression [-Wdangling]
8 | auto [min3, max3] = std::ranges::minmax(2, 1);
| ^
prog.cc:8:46: warning: temporary whose address is used as value of local variable '[min3, max3]' will be destroyed at the end of the full-expression [-Wdangling]
8 | auto [min3, max3] = std::ranges::minmax(2, 1);
| ^
4 warnings generated.
gcc 13.2.0
$ g++ prog.cc -Wall -Wextra -std=c++2a -O2
prog.cc: In function 'int main()':
prog.cc:6:8: warning: possibly dangling reference to a temporary [-Wdangling-reference]
6 | auto [min1, max1] = std::minmax(2, 1);
| ^~~~~~~~~~~~
prog.cc:6:34: note: the temporary was destroyed at the end of the full expression 'std::minmax<int>(2, 1)'
6 | auto [min1, max1] = std::minmax(2, 1);
| ~~~~~~~~~~~^~~~~~
prog.cc:11:34: warning: '<anonymous>' is used uninitialized [-Wuninitialized]
11 | std::cout << "min=" << min1 << " max=" << max1 << std::endl;
| ^~~~~~~
prog.cc:6:34: note: '<anonymous>' was declared here
6 | auto [min1, max1] = std::minmax(2, 1);
| ~~~~~~~~~~~^~~~~~
prog.cc:11:45: warning: '<anonymous>' is used uninitialized [-Wuninitialized]
11 | std::cout << "min=" << min1 << " max=" << max1 << std::endl;
| ^~~~
prog.cc:6:34: note: '<anonymous>' was declared here
6 | auto [min1, max1] = std::minmax(2, 1);
| ~~~~~~~~~~~^~~~~~
prog.cc:13:34: warning: '<anonymous>' is used uninitialized [-Wuninitialized]
13 | std::cout << "min=" << min3 << " max=" << max3 << std::endl;
| ^~~~~~~
prog.cc:8:42: note: '<anonymous>' was declared here
8 | auto [min3, max3] = std::ranges::minmax(2, 1);
| ~~~~~~~~~~~~~~~~~~~^~~~~~
prog.cc:13:45: warning: '<anonymous>' is used uninitialized [-Wuninitialized]
13 | std::cout << "min=" << min3 << " max=" << max3 << std::endl;
| ^~~~
prog.cc:8:42: note: '<anonymous>' was declared here
8 | auto [min3, max3] = std::ranges::minmax(2, 1);
| ~~~~~~~~~~~~~~~~~~~^~~~~~