I was wrong assuming that the expression QList() << 7 << 9 returns a temporary.
Yes, QList() creates a temporary, then is gets 7 and 9 appended, which each time a value is appended by calling <<, this call returns QList& which is not a temporary object but a reference to a temporary.
(because QList:perator << return QList&). Note that returned QList& is not a temporary anymore, but a lvalue itself.
Conclusion
1) QList<int> & l1 = QList<int>(); //illegal c++, rvalue (temporary) may only be bound to const&; compilers are smart and warn about this!
2) const QList<int> & l2 = QList<int>(); //perfectly valid, legal c++, const& binds to directly to the temporary/rvalue (list ctor called; no dtor called)
3) QList<int> & l3 = QList<int>() << 7 << 9; //non const reference is dangerously!! bound to the result of the expression QList() << 7 << 9, a reference! to a temporary itself, and temporary is destroyed immediately (dtor is called and I get a dangling reference)
4) const QList<int> & l4 = QList<int>() << 7 << 9; //I was hoping to get const reference bound to the temporary, therefore to keep temporary alive; but in this case, const is useless, bounds to a ref to a temporary and temporary gets destroyed, same as in 3); dtor is called, I get a dangling reference
While 2) is a great option in c++ and 1) is discarded by the compiler, 3) and 4) are similarly dangerous and unfortunately silent. I learned something :-)
Thank you all
Bookmarks