C++ compiler support to detect returning a reference to a temporary object

118 Views Asked by At

There is a snipped code, that returns a reference to a temporary object:

#include <iostream>
#include <string>

const std::string& forward(const std::string& s)
{
    return s;
}

int main()
{
    const std::string& hello = forward("this is a random string with a reference to a temporary object");
    std::cout << hello << "\n";
}

I compiled the snipped as following:

g++ -std=c++20 -Wpedantic -Wall test.cpp -o test

clang++ -std=c++20 -Wpedantic -Wall test.cpp -o test

and I expected a warning message warning: returning reference to temporary, but there was no warning about this bugged use of the "forward()" function.

Does any C++ compiler support detection of such cases when returning temporary objects?

1

There are 1 best solutions below

1
user17732522 On BEST ANSWER

There is no problem with the function itself or the call to it. When forward returns the temporary object is still alive. Its lifetime only ends after the initialization of hello. Therefore a warning saying that the function returns a dangling reference wouldn't be correct. The result of the function call can still be used in the same full-expression without anything dangling.

You only have a problem after the initialization of hello when hello immediately becomes dangling. And then the use in std::cout << hello << "\n"; has UB.

To recognize that the initialization of hello causes access to a dangling pointer later in the output statement, the compiler needs to inline at least forward. So it wouldn't be surprising if the compiler's analysis can only detect this issue with optimizations enabled.

That seems to be exactly the case here for GCC 12 and later, which provides the warning with optimizations enabled (at least -O1) and -Wall. Clang and MSVC don't seem to perform such an analysis at the moment.

I would however expect static analyzers like clang-analyze as well as runtime sanitizers like ASAN (-fsanitize=address for GCC/Clang) to detect this issue (and ASAN does for both GCC and Clang at any optimization level in my tests).