简体   繁体   中英

Pointer to a variable stored in the stack

So basically I have an object created that is stored in the heap (using new to create it) and this object holds a pointer of a variable (Vector3 in this case, but it doesn't matter) that is stored in the stack (created using Vector3(0, 0, 0)).

I am passing the pointer to the Vector3 stored in the stack like so:

new AudioSource(some other stuff, &(e1->getPosition()))

e1 is another pointer to an object in the heap, but I don't think it matters.

So I assume that when I update the position (for example e1->setPosition(something) then since the object that I want to keep a pointer of this position has the pointer and not a copy of the position, it should automatically hold the new values that are stored in that memory address.

However, that is not the case. I update the position of the object that has it, but it isn't updated in my other object that holds the pointer.

Could it be because position is stored in the stack?

Thank you for reading, sorry if you didn't understand something.

Your getPosition is probably doing something like:

Vector3 getPosition() { return position; }

Because of this, you are returning a copy of the position vector and therefore not the object you really want. You should be doing something like this:

Vector3* getPositionPtr() { return &position; }

It was kind of obvious to be honest, my getter (getPosition()) does not return a reference to the actual variable stored in the stack, therefore I was getting a pointer to a temporary copy. Thanks @Vivick for the answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM