简体   繁体   English

C ++“警告:返回对临时的引用” - 但事实并非如此

[英]C++ “warning: returning reference to temporary ” - But it isn't

I have a very simple method, and const overload of it. 我有一个非常简单的方法,它的const重载。

Sy_animatable::PropertyTimeLine&
Sy_animatable_imp::getPropertyTimeLine( const QString& property )
{
    if ( !properties_.contains( property ) ) {
        throw Sy_unknownAnimPropertyException( property );
    }

    return properties_[property];
}

const Sy_animatable::PropertyTimeLine&
Sy_animatable_imp::getPropertyTimeLine( const QString& property ) const
{
    if ( !properties_.contains( property ) ) {
        throw Sy_unknownAnimPropertyException( property );
    }

    return properties_[property];  // "warning: returning reference to temporary"
}

I don't understand the warning for two reasons: 我不明白这个警告有两个原因:

  1. properties_ is a member variable and it's subscript operator (it's a QMap ) returns a reference, so there shouldn't be any temporaries and it is persistant for the lifetime of the object. properties_是一个成员变量,它的下标运算符(它是一个QMap )返回一个引用,因此不应该有任何临时值,并且它在对象的生命周期内是持久的。
  2. Why is the warning appearing in the const overload and not the original? 为什么警告出现在const重载而不是原始?

I could #pragma the line to hide the warning, but I really want to know why it is giving me the warning - any suggestions? 我可以#pragma该行来隐藏警告,但我真的想知道为什么它会给我警告 - 任何建议?

Looks like the [] -operator for QMap has strange semantics that sometimes generate a const-reference to a temporary (if there's no element with the given key), and the lifetime of that one isn't extended far enough. 看起来QMap[] QMap具有奇怪的语义,有时会生成对临时的const引用(如果没有给定键的元素),并且该生命周期的延长不够远。

Try return properties_.find(property).value(); 尝试return properties_.find(property).value(); instead. 代替。

In QMap, operator[]() is kind of quirky; 在QMap中, operator[]()有点古怪; it can both insert (key, value) pairs in the map, and be used for looking up a value. 它既可以在地图中插入(键,值)对,也可以用于查找值。 The documentation states: 文件说明:

To look up a value, use operator or value(): 要查找值,请使用operator或value():

 int num1 = map["thirteen"]; int num2 = map.value("thirteen"); 

If there is no item with the specified key in the map, these functions return a default-constructed value. 如果映射中没有指定键的项,则这些函数将返回默认构造的值。

QMap::value() returns a default-constructed value if the specified key isn't in the map -- which means a value is created using the default constructor. 如果指定的键不在映射中, QMap::value()将返回默认构造的值 - 这意味着使用默认构造函数创建值。 This is the temporary the warning you are getting is referring to. 这是你得到的警告的临时性。 While operator[]() will not silently insert a (key, value) pair if it already exists (but will if it doesn't), using .value() is the way to go although I'm not sure the warning will go away. 虽然operator[]()不会以静默方式插入(key,value)对(如果它已经存在)(但如果不存在),使用.value()是可行的方法虽然我不确定警告会走开。

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

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