警告:返回临时引用(来自const)

DrH*_*ell 5 c++ temporary

早上好:情况如下

.h文件

extern const std::string void_string_;
extern const int zero_int;

template <typename Class>    
inline const Class& zero() 
{
   // an error message
}

template <>
inline const int& zero<int>()
{
    return zero_int;
}

template <>
inline const std::string& zero<std::string>()
{
    return void_string_;
}
Run Code Online (Sandbox Code Playgroud)

.cpp文件

const std::string void_string_="";
const int zero_int=0;
Run Code Online (Sandbox Code Playgroud)

然后我用这两个函数调用

zero<int>()
zero<string>()
Run Code Online (Sandbox Code Playgroud)

现在,编译器给我一个警告

zero<int>()
Warning: returning reference to temporary
Run Code Online (Sandbox Code Playgroud)

好吧,我知道,理论上,为什么我会收到警告:当我使用临时引用时.没关系.仍然我不明白为什么const int zero_int; 被认为是暂时的.

谢谢你的任何澄清.

编辑:根据评论的建议,我编辑了Class&zero模板.虽然最初我不能包含错误代码(因为错误消息是一个函数),我清理它以在此处发布并有效地在过程中我理解错误的原因.特别:

template <typename Class>    
inline const Class& zero() 
{
    std::cout << "No!" << std::endl; // substitutes the original error message
    return zero_int;
}
Run Code Online (Sandbox Code Playgroud)

当我在一行代码中调用时,会发生错误

zero<long long int>() 
Run Code Online (Sandbox Code Playgroud)

这实际上创造了一个暂时的.试:

template <typename Class>    
inline const Class& zero() 
{
    std::cout << "No!" << std::endl; // substitutes the original error message
    return (Class&)zero_int;
}
Run Code Online (Sandbox Code Playgroud)

删除警告,但显然给出了另一个"小"问题(即:结果不是0,而是一些随机数,可能与程序读取的其他字节有关)

在这一点上,我做的唯一改变是保留Class&zero()undefined.

template <typename Class>    
inline const Class& zero(); // left undefined by purpose
Run Code Online (Sandbox Code Playgroud)

通过这种方式获得完整的错误,如:

undefined reference to `long long const& zero<long long>()'
Run Code Online (Sandbox Code Playgroud)

当我必须定义正确的专业化时,它会提醒我.

谢谢你指点我正确的方向.