简体   繁体   中英

c++ vector push_back with pointers

I'm trying to get my head around solving the following problem. I have the following function which accepts a const reference to an object. What I want to do, is give storage, a pointer to the object component is referencing. However, when I call storage.push_back() changes the object component is referencing (it's member data gets corrupted)

I'm just trying to store a pointer to the same object component is referencing, not alter the object at all.

void InputSystem::RegisterInputAcceptingEntity(const PlayerInputComponent &component) {

    auto *cpy = &component;

    std::vector<const PlayerInputComponent*> storage;
    storage.push_back(cpy);
}

Why would the above code at all change the object component is referencing?

edit: Ok I edited the vector to contain constant pointers.

Here are some screenshots showing exactly what is happening. Here in the callee, if we inspect the argument that is going to be passed by reference, we can see the input_component member is not corrupted. 在此处输入图片说明 url to image: http://i.imgur.com/lKpRm.png

However, in the second image, just after stepping into the above said method:

在此处输入图片说明 url to image: http://i.imgur.com/x0Vdn.png

I've been under the impression that passing by const reference, there should be no way for the objects to differ inside/outside the function. I don't see why the object would be altered at all, if passed by const reference.

First, run your code through valgrind and see where the corruption is actually occurring. Pushing a pointer onto an array should not do anything to the data being pointed to.

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