Question

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?

Was it helpful?

Solution 2

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).

OTHER TIPS

The language you are looking for is: "Returning a QSharedPointer by value" - that is precisely what you're doing. Where you allocate it within a function is an orthogonal issue. You can allocate it on the heap, if you so wish, of course.

The code below won't leak memory and doesn't invoke any undefined behavior. The temporary instance of the shared pointer allocated on the heap in answer1 will be deallocated by its shared pointer. The pointed-to value in the Q_ASSERT will live until the statement finishes.

#include <QSharedPointer>
#include <memory>

QSharedPointer<int> answer1() {
  // shared-pointer-to-integer is on the heap
  std::shared_ptr<QSharedPointer<int>> ptr(new QSharedPointer<int>(new int));
  **ptr = 42;
  return *ptr;
}

QSharedPointer<int> answer2() {
  // shared-pointer-to-integer is a local value
  QSharedPointer<int> ptr = answer1();
  return ptr;
}

int main()
{
   Q_ASSERT(*answer2() == 42);
   return 0;
}

There's IIRC nothing in the standard that says that returning anything from a method/function is done using a stack, a register, or anything else in particular. There can be goblins carrying around values carved on slate tablets. As far as C++ is concerned, stack is a class in the std namespace, and there's no other stack to speak about. The language is completely stack-agnostic at the specification level. Stack is an implementation detail that you needn't worry about at this point. You're basically introducing a concept that doesn't belong here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top