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

cma*_*t85 2 c++ qt gcc

我有一个非常简单的方法,它的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"
}
Run Code Online (Sandbox Code Playgroud)

我不明白这个警告有两个原因:

  1. properties_是一个成员变量,它的下标操作符(它是a QMap)返回一个引用,因此不应该有任何临时值,并且它在对象的生命周期内是持久的.
  2. 为什么警告出现在const重载而不是原始?

我可以#pragma用线来隐藏警告,但我真的想知道为什么它会给我警告 - 任何建议?

Ker*_* SB 8

看起来[]-operator for QMap有奇怪的语义,有时会产生一个临时的const引用(如果没有给定键的元素),并且那个的生命周期不够扩展.

试试吧return properties_.find(property).value();.