警告:返回对临时的引用

2022-01-05 00:00:00 reference c++

我有这样的功能

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.

相关文章