There is no link to std :: min in lib ++

It is well known (or should be) that binding the result of std::min to a const link is a very bad idea when one of the arguments to std::min is r, since linking const links is not propagated through the return function. So the following code

 #include <iostream> #include <algorithm> int main() { int n = 42; const int& r = std::min(n - 1, n + 1); // r is dangling after this line std::cout << r; } 

should cause undefined behavior since r hangs. And indeed, when compiling with gcc5.2 with -Wall -O3 compiler spits

warning: <anonymous> used uninitialized in this function [-Uniminate.]

However, compiling with clang (llvm 7.0.0) using the same flags (even including -Wextra ) does not give a warning, and the program seems to "work", that is, displays 41 .

Question: Is clang using the "safe" version of std::min ? How is the version that uses some SFINAE to return by value when one of the arguments is an rvalue value? Or is it just that you don’t need to emit any diagnostics, and does the program “happen” to get the “correct” result in this UB script?

+6
source share
1 answer

This is UB. libC ++ does not protect you from this.

+6
source

All Articles