C ++ - temporary variables and their lifespan

This question can be considered as the following question: temporary life of a C ++ variable .

Containers

Qtsupport initialization syntax stream-like. Now, when I write the following code, mine is QVectordestroyed immediately after assignment and the link becomes drooping.

const QVector<QString>& v = QVector<QString>() << "X" << "Y" << "Z";

The corresponding one operator<<is implemented as follows:

inline QVector<T> &operator<< (const T &t)
{ append(t); return *this; }

As far as I know, 10.4.10 Temporary Objectsit claims that the lifetime of a temporary object extends to match the lifetime of a correlation link constto it.

However, in this case, the temporary object is QVector<QString>() destroyed earlier.

I assume that this is probably due to the fact that the last operation returns QVector<QString>&and does not need to know anything about the temporary lifetime QVector<QString>, but this explanation is not strict and may be incorrect.

So why is this happening?

+5
source share
1 answer

The lifetime of a temporary extension only extends if it is associated with a reference constant:

const QVector<QString>& v = QVector<QString>();

- -. , - (), ( ). , . , , v .

( ++ " " , rvalue, .. =delete rvalue- <<.)

+7

All Articles