does a pointer to an element of a vector remain af

2020-04-12 10:21发布

I'm working on a collision engine and more specifically, I am trying to make a vector of relevant bodies in the world. To be able to access a specific body in the vector of bodies in the world that represents a specific object, I need to know which specific body represents that object. To do this I want to return a pointer to the body in the vector of bodies when you add a new body, but what happens when I remove a body? more specifically, what if I remove a body that is before the current body in the list of bodies, and the body's position in the array changes. Does my pointer still point to the correct location in memory?

1条回答
干净又极端
2楼-- · 2020-04-12 10:34

After removing an element in a vector all elements after the removed element will be moved one position left. So either the pointer will point to some other element or to the deleted element if it was the last element in the vector.

If you add a new element then the vector can reallocate memory. So all pointers to the elements of the vector will be invalid.

查看更多
登录 后发表回答