Search code examples
c++referenceclang++libc++object-lifetime

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?


Solution

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