简体   繁体   English

警告:返回临时引用

[英]warning: returning reference to temporary

I have a function like this 我有这样的功能

const string &SomeClass::Foo(int Value)
{
    if (Value < 0 or Value > 10)
        return "";
    else
        return SomeClass::StaticMember[i];
}

I get warning: returning reference to temporary . 我收到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. 我认为函数返回的两个值(引用const char *“”和对静态成员的引用)不能是临时的。

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. ""不是std::string ,因此编译器会尝试找到将其转换为一个的方法。 And by using the string( const char* str ) constructor it succeeds in that attempt. 通过使用string( const char* str )构造函数,它成功完成了该尝试。 Now a temporary instance of std::string has been created that will be deleted at the end of the method call. 现在创建了一个临时的std::string实例,该实例将在方法调用结束时删除。 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 . 我建议您将返回类型更改为const string或将""存储在SomeClass的成员或静态变量中。

This is the exemplary of trying to optimize code in c++. 这是尝试在c ++中优化代码的示例。 I did it, everybody did it... It is worth mentioning that this is the classical example that is eligible to return value optimization. 我做到了,每个人都做到了......值得一提的是,这是有资格返回价值优化的经典例子。

Like ttvd said the correct answer is to return const std::string and not a reference to it and to let the compiler optimise it. 就像ttvd所说,正确的答案是返回const std :: string而不是对它的引用,并让编译器优化它。

If you trust the interpreter of your favorite language to optimize behind you, you shouldn't try to be too smart with C++ either. 如果您相信您喜欢的语言的翻译能够在您身后进行优化,那么您也不应该尝试使用C ++过于聪明。

The problem is in the first line. 问题出在第一行。 "" will be turned into an std::string , as it has a valid constructor that takes a char* . ""将变成std::string ,因为它有一个带有char*的有效构造函数。 That std::string will be an anonymous object, which is temporary, and you return its reference. 那个std::string将是一个匿名对象,它是临时的,你返回它的引用。

Like Shaggy Frog said, it converts "" to a temporary std::string object and since your method signature is std::string& it attempts to return a reference to it, hence you get the warning. 就像Shaggy Frog所说,它将“”转换为临时的std :: string对象,因为你的方法签名是std :: string,它会尝试返回对它的引用,因此你会得到警告。 One workaround may be to return the std::string by value (const std::string SomeClass::Foo(..)). 一种解决方法可能是按值返回std :: string(const std :: string SomeClass :: Foo(..))。

要避免的另一种可能性是声明要返回的内容为static,只使用return by reference

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM