Search code examples
c++qtsmart-pointersqsharedpointer

Allocating and returning from function a QSharedPointer on the stack


Unlike a dumb pointer, I would expect that I could create a QSharedPointer on the stack in a function and then return it as return value for assignment to another QSharedPointer of the same type, right? Normally, such a pointer would point to memory that is now out of scope and therefore the pointer is not valid, but a QSharedPointer will ensure it is retained in memory if another copy of it remains, I would expect. Is this correct?


Solution

  • The pointer can live on the stack, but the thing to which it points must be on the heap. (Note that the same applies for an ordinary pointer as well as a QSharedPointer or a std::shared_ptr).