C++ "warning: returning reference to temporary " - 但事实并非如此
C++ "warning: returning reference to temporary " - But it isn't
>我有一个非常简单的方法,并且常量重载它。
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"
}
我不明白警告有两个原因:
-
properties_
是一个成员变量,它的下标运算符(它是一个QMap
)返回一个引用,所以不应该有任何临时变量,并且在对象的生存期内是持久的。 - 为什么警告出现在 const 重载中而不是原始警告中?
我可以#pragma
行来隐藏警告,但我真的很想知道为什么它会给我警告 - 有什么建议吗?
看起来QMap
的[]
运算符具有奇怪的语义,有时会生成对临时的常量引用(如果没有具有给定键的元素),并且该运算符的生命周期还不够长。
请尝试return properties_.find(property).value();
。
在QMap中,operator[]()
有点古怪;它既可以在映射中插入(键,值)对,也可以用于查找值。文档指出:
要查找值,请使用运算符或 value():
int num1 = map["thirteen"]; int num2 = map.value("thirteen");
如果映射中没有具有指定键的项目,则这些函数 返回默认构造的值。
如果指定的键不在映射中,QMap::value()
返回默认构造的值 - 这意味着使用默认构造函数创建值。这是您收到的警告所指的临时警告。虽然如果(键,值)对已经存在,operator[]()
不会默默插入(但如果不存在,则会)插入),使用.value()
是要走的路,尽管我不确定警告是否会消失。
相关文章:
- 如何理解"Temporary objs are destroyed as the last step in evaluating the full-expression"?谁能用一些简单的例子来说明这
- 隐式转换产生"error: taking address of temporary"(GCC 与 clang)
- 为什么我收到以下错误:"returning reference to temporary [-Werror=return-local-addr]"
- 为什么"no temporary std::string objects would arise"在有效的现代C++的第25项中说?
- 当"taking address of temporary"错误妨碍干净的代码时
- MinGW在代码块中构建时的ar.exe "could not create temporary file whilst writing archive: no more archived files
- 为什么不触发"returning reference to temporary object"编译器警告?
- 生成(并非如此)出现特定字符串的随机字符串
- 链表显示;缺少..但事实并非如此
- C++ 矢量下标超出范围(但事实并非如此)
- 忽略"taking address of temporary"错误
- 视觉C++将其视为常量,而事实并非如此
- "taking address of temporary"警告
- 此代码看起来像是删除了此对象,但事实并非如此
- 为什么编译器在返回对局部变量的局部引用时不警告"returning address of local variable or temporary"?
- C++ "warning: returning reference to temporary " - 但事实并非如此
- 如何避免"taking address of temporary"没有问题?
- Temporary在首先被强制转换为引用类型时仍然绑定到引用
- C++:"invalid initialization of non-const reference of type ‘List&’ from a temporary of type ‘List*’"
- 使用boost::optional时避免使用temporary