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
.
这篇关于警告:返回对临时的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:警告:返回对临时的引用


基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01