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.
这篇关于警告:返回对临时的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:警告:返回对临时的引用
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
