0

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.

3
  • 1
    The getter probably doesn't return a reference thus making your pointer a pointer to a temporary copy Commented Feb 25, 2018 at 23:42
  • 2
    Please provide some code that exhibits the problem, the text is useful but code would be more precise and we would be able to address problems directly Commented Feb 25, 2018 at 23:44
  • I don't even know how I didn't notice that, I feel so dumb. Thanks a lot. Commented Feb 25, 2018 at 23:46

2 Answers 2

1

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& getPosition() { return position; }
Sign up to request clarification or add additional context in comments.

1 Comment

Returning a reference would be more idiomatic.
0

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.

1 Comment

If you used a real compiler like GCC it wouldn't have let you do this. The standard says you can't take the address of an rvalue, and preventing errors like this is exactly why! Sadly Visual Studio doesn't care :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.