警告:返回对临时的引用 [英] warning: returning reference to temporary

查看:20
本文介绍了警告:返回对临时的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的功能

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.

这篇关于警告:返回对临时的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆