Antithesis
Antithesis

Reputation: 337

Accessing stack objects outside a function

If I have a function that creates a STL object on the stack and adds them to the stack. For example say I make std::pair on the stack and add them to a std::queue that is made on the heap. Now if I pass the queue outside the function, can a different function that takes the queue as a parameter access the std::pair objects.

Upvotes: 0

Views: 94

Answers (3)

Mike Precup
Mike Precup

Reputation: 4218

Depends on a few factors you don't mention.

The first thing to check is whether you're copying the object into the queue, or copying a pointer to the object into the queue. Here's examples of each.

std::queue<A> copyQueue;
std::queue<A*> pointerQueue;

void addCopy(A a) {
  copyQueue.add(a);
}

void addPointer(A a) {
  pointerQueue.add(&a);
}

If it's storing copies of the objects, then anything with access to the queue can access that object without issue. If it's storing pointers, it depends on whether that stackframe has been reclaimed. If the stackframe is untouched, accessing that memory will be fine. Otherwise, the value will be garbage.

Legal example: Function A adds a pointer to a stack allocated object to std::queue Q, and then passes Q to function B. Since function A has not yet returned, function B can access the object in Q without issue.

Garbage example: Function A adds a pointer to a stack allocated object to std::queue Q, and then returns Q to its calling function B. Since function A has returned, function B will receive garbage if it tries to access the object in Q.

Upvotes: 2

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22224

When you push an object (std::pair in your case) in a std::queue it is copied from local scope into the queue. Therefore when the local object goes out of scope and is deleted, its copy in the queue is still valid until the queue itself gets deleted.

As a side note prefer emplace over push as it will construct the std::pair in place in the queue instead of copying.

Upvotes: 1

Heto
Heto

Reputation: 595

Yes, because when you "add" the object from the stack to object from the heap you will do a copy of the information that resides on stack to the "heap".

Upvotes: 0

Related Questions