C++ 不能返回局部变量的引用

// max.hpp

#include <iostream>
// 模板被编译了两次,分别发生在:
// 1. 实例化之前,先检查模板代码本身,查看语法是否正确;这里会发现错误的语法,如遗漏分号等。
// 2. 实例化期间,检查模板代码,查看是否所有的调用都有效。在这里也会发现无效的调用,如该实例化类型不支持某些函数调用等。

template <typename T1, typename T2>
inline T1 const& min(T1 const& a, T2 const& b)
{
    return a < b ? a : b;
}

 

// max.cpp

#include <iostream>
#include <string>
#include "max.hpp"

int main()
{
    std::cout << "min(4, 4.5): " << min(4, 4.5) << std::endl;
    return 0;
}

 

编译时告警:
In file included from max.cpp:4:0:
max.hpp: In instantiation of ‘const T1& min(const T1&, const T2&) [with T1 = int; T2 = double]’:
max.cpp:21:47:   required from here
max.hpp:17:24: warning: returning reference to temporary [-Wreturn-local-addr]
     return a < b ? a : b;
                        ^

执行时报错:
Segmentation fault (core dumped)

posted @ 2023-10-26 21:47  牛博张  阅读(16)  评论(0编辑  收藏  举报