Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No dangling reference for std::min in libc++

It is well known (or it should be) that binding the result of std::min to a const reference is a very bad idea, whenever one of the arguments of std::min is a rvalue, since const reference binding is not propagated through function return. 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 produce undefined behaviour since r is dangling. And indeed, when compiling with gcc5.2 with -Wall -O3 the compiler spits

warning: <anonymous> is used uninitialized in this function [-Wuninitialized]

However, compiling with clang (llvm 7.0.0) using the same flags (even including -Wextra) does not emit any warning, and the program seems to "work", i.e. displays 41.

Question: Is the clang using a "safe" version of std::min? Like a version that uses some SFINAE to return by value whenever one of the arguments is a rvalue? Or is it simply not required to emit any diagnostic and the program "happens" to produce the "right" result in this UB scenario?

like image 928
vsoftco Avatar asked Oct 03 '15 00:10

vsoftco


1 Answers

It is UB. libc++ does not protect you from this in any way.

like image 181
Howard Hinnant Avatar answered Sep 17 '22 15:09

Howard Hinnant