C++ "warning: returning reference to temporary " - 但事实并非如此

C++ "warning: returning reference to temporary " - But it isn't

本文关键字:并非如此 temporary 事实 reference warning returning C++ to      更新时间:2023-10-16

>我有一个非常简单的方法,并且常量重载它。

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"
}

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

  1. properties_是一个成员变量,它的下标运算符(它是一个QMap)返回一个引用,所以不应该有任何临时变量,并且在对象的生存期内是持久的。
  2. 为什么警告出现在 const 重载中而不是原始警告中?

我可以#pragma行来隐藏警告,但我真的很想知道为什么它会给我警告 - 有什么建议吗?

看起来QMap[]运算符具有奇怪的语义,有时会生成对临时的常量引用(如果没有具有给定键的元素),并且该运算符的生命周期还不够长。

请尝试return properties_.find(property).value();

在QMap中,operator[]()有点古怪;它既可以在映射中插入(键,值)对,也可以用于查找值。文档指出:

要查找值,请使用运算符或 value():

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

如果映射中没有具有指定键的项目,则这些函数 返回默认构造的值。

如果指定的键不在映射中,QMap::value()返回默认构造的值 - 这意味着使用默认构造函数创建值。这是您收到的警告所指的临时警告。虽然如果(键,值)对已经存在,operator[]()不会默默插入(但如果不存在,则会)插入),使用.value()是要走的路,尽管我不确定警告是否会消失。

相关文章: