[英]C++ - temporary variables and their lifetime
This question can be considered a follow-up to the following question: C++ temporary variable lifetime . 这个问题可以被认为是以下问题的后续问题: C ++临时变量生命周期 。
Qt
containers support the stream-like
initialization syntax. Qt
容器支持stream-like
初始化语法。 Now, when I write the following code, my QVector
is destructed right after assignment and the reference becomes dangling. 现在,当我编写以下代码时,我的
QVector
在分配后QVector
被破坏,并且引用变为悬空。
const QVector<QString>& v = QVector<QString>() << "X" << "Y" << "Z";
Corresponding operator<<
is implemented the following way: 对应的
operator<<
以下列方式实现:
inline QVector<T> &operator<< (const T &t)
{ append(t); return *this; }
As far as I know, 10.4.10 Temporary Objects
states that the lifetime of a temporary object is extended to match the lifetime of the correspnding const
reference to it. 据我所知,
10.4.10 Temporary Objects
声明10.4.10 Temporary Objects
的生命周期被扩展以匹配对应的const
引用的生命周期。
However, in this case the temporary object QVector<QString>()
is destructed earlier. 但是,在这种情况下,临时对象
QVector<QString>()
被破坏。
I guess that probably this happens due to the fact that the last operation returns a QVector<QString>&
and shouldn't know anything about the lifetime of the temporary QVector<QString>
, but this explanation isn't strict and might be wrong. 我想这可能是因为最后一个操作返回一个
QVector<QString>&
并且不应该知道临时QVector<QString>
的生命周期的QVector<QString>
,但这个解释并不严格,可能是错误的。
So, why does this happen? 那么,为什么会这样呢?
The lifetime of a temporary is only extended if it is bound to a const-reference: 临时的生命周期只有在绑定到const-reference时才会扩展:
const QVector<QString>& v = QVector<QString>();
However, in your code you are not binding the temporary to anything. 但是,在您的代码中,您不会将临时绑定到任何内容。 Rather, you're calling a member function (of the temporary), which returns a reference (to the temporary).
相反,你正在调用一个成员函数(临时的),它返回一个引用(到临时)。 The result of this function call is no longer a temporary object, but just a plain reference.
此函数调用的结果不再是临时对象,而只是一个简单的引用。 The original temporary object expires at the end of the full expression in which it appears, and the reference
v
becomes dangling. 原始临时对象在其出现的完整表达式的末尾到期,并且引用
v
变为悬空。
(In the new C++, it is possible to prohibit such "accidents" by virtue of rvalue-qualified member functions, ie you could =delete
the rvalue version of the <<
operator.) (在新的C ++中,可以通过rvalue限定的成员函数禁止此类“事故”,即您可以
=delete
<<
运算符的rvalue版本。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.