有一段代码,返回对临时对象的引用:
#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";
}
我编译的片段如下:
g++ -std=c++20 -Wpedantic -Wall test.cpp -o test
clang++ -std=c++20 -Wpedantic -Wall test.cpp -o test
我期待一条警告消息
warning: returning reference to temporary
,但是没有关于这个有问题的“forward()”函数的警告。
是否有任何 C++ 编译器支持在返回临时对象时检测此类情况?
函数本身或对它的调用都没有问题。当
forward
返回时,临时对象仍然存在。它的生命周期仅在 hello
的初始化之后结束。因此,警告说该函数返回悬空引用是不正确的。函数调用的结果仍然可以在同一个完整表达式中使用,没有任何悬空。
当
hello
立即变为悬空时,hello
的初始化后,您只会遇到问题。然后std::cout << hello << "\n";
中的使用有UB.
要认识到
hello
的初始化会导致稍后在输出语句中访问悬空指针,编译器需要至少内联 forward
。因此,如果编译器的分析只能在启用优化的情况下检测到这个问题,那就不足为奇了。
这似乎正是 GCC 12 及更高版本的情况,它提供了启用优化的警告(至少
-O1
)和-Wall
。 Clang 似乎没有执行此分析。