警告:返回引用临时 [英] warning: returning reference to temporary
问题描述
我有这样的功能
const string &SomeClass::Foo(int Value)
{
if (Value < 0 or Value > 10)
return "";
else
return SomeClass::StaticMember[i];
}
我得到警告: code>。这是为什么?我认为函数返回的两个值(引用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.
推荐答案
p>这是一个不必要的隐式转换发生的例子。 不是一个std :: string,所以编译器试图找到一种方法将其变成一个。通过使用字符串(const char * str)构造函数,它在这个尝试中成功。
现在已经创建了一个std :: string的临时实例,它将在方法调用结束时被删除。因此,引用一个在方法调用后不再存在的实例显然不是一个好主意。
我建议您将返回类型更改为const字符串或将存储在SomeClass的成员或静态变量中。
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. I'd suggest you either change the return type to const string or store the "" in a member or static variable of SomeClass.
这篇关于警告:返回引用临时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!