warning: returning reference to temporary(警告:返回对临时的引用)
问题描述
我有这样的功能
const string &SomeClass::Foo(int Value)
{
if (Value < 0 or Value > 10)
return "";
else
return SomeClass::StaticMember[i];
}
我收到警告:返回对临时的引用
.这是为什么?我认为函数返回的两个值(对 const char* "" 的引用和对静态成员的引用)不能是临时的.
I get warning: returning reference to temporary
. Why is that? I thought the both values the function returns (reference to const char* "" and reference to a static member) cannot be temporary.
推荐答案
这是发生不需要的隐式转换的示例.""
不是 std::string
,所以编译器试图找到一种方法将它变成一个.并且通过使用 string( const char* str )
构造函数,它在该尝试中取得了成功.现在已经创建了一个 std::string
的临时实例,它将在方法调用结束时删除.因此,引用在方法调用后不再存在的实例显然不是一个好主意.
This is an example when an unwanted implicit conversion takes place. ""
is not a std::string
, so the compiler tries to find a way to turn it into one. And by using the string( const char* str )
constructor it succeeds in that attempt.
Now a temporary instance of std::string
has been created that will be deleted at the end of the method call. Thus it's obviously not a good idea to reference an instance that won't exist anymore after the method call.
我建议您将返回类型更改为 const string
或将 ""
存储在 SomeClass
的成员或静态变量中.
I'd suggest you either change the return type to const string
or store the ""
in a member or static variable of SomeClass
.
这篇关于警告:返回对临时的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:警告:返回对临时的引用


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07