Is QList out-of-scope when function returns?
-
While debugging a problem in my Qt application, I came across the following snippet of code (which I have shrunk for the purpose of this question) that I don't quite understand. The snippet is from the Qt 6.6.1 library source code.
QList<qreal> ChartValueAxisY::calculateLayout() const { QList<qreal> points; for (int i = 0; i < 10; ++i) { points[i] = qreal(i); } return points; }
My understanding is that the QList of qreal values is stored on the STACK (because the keyword 'new' is not used), and the 'return points' is returning a pointer to the QList. But to me, it seems wrong to return a pointer to values on the stack that are going to become 'out-of-scope' after the function returns.
Could some help explain what is going on with respect to the STACK and my out-of-scope concerns with this code that exists in the Qt library source code.
Thanks.
-
@EricR said in Is QList out-of-scope when function returns?:
My understanding is that the QList of qreal values is stored on the STACK (because the keyword 'new' is not used), and the 'return points' is returning a pointer to the QList.
First part is correct: your QList is allocated on the stack.
Second part is wrong: calculateLayout returns QList by value, not a pointer - that means points is copied.
If calculateLayout would return a pointer (QList<qreal>* ChartValueAxisY::calculateLayout()) then it would be a problem. -
@EricR
There is no "out of scope" here. TheQList
itself is stored on the stack, but all the contents are stored on the heap. Yes you can return aQList
from a function. That is just a very small stack object, which is copied as a return result. And because of Qt's Implicit Sharing it actually just increments a counter, the elements/list are not actually copied a second time. But that part is incidental to your question. -