简体   繁体   English

无法获取标准向量中元素的指针

[英]cant take pointer of an element in a std vector

I have a problem with std::vector 我对std :: vector有问题

class myType
{
    int i;
};

int main()
{
    myType a1;
    myType a2;
    std::vector<myType> V;
    V.push_back(a1);
    myType* a1ptr = &V.back();
    V.push_back(a2);
}

it all works fine before I add a2, the ptr is point to some meaningful memory. 在添加a2之前一切正常,ptr指向一些有意义的内存。 but as soon as i added a2, the ptr is still point to the same place but with some garbage memory. 但是,一旦我添加了a2,ptr仍然指向同一位置,但有一些垃圾内存。

how is this happened? 这是怎么回事?

When you add a2 into your vector, the vector must resize. 将a2添加到向量中时,向量必须调整大小。 This means new memory is allocated and the old vector copied into this new (larger) memory. 这意味着将分配新的内存,并将旧的向量复制到该新的(较大的)内存中。 The old memory is then deallocated. 然后将旧内存释放。 Your pointer is left dangling into this (old) deallocated memory. 您的指针悬空到这个(旧的)已释放的内存中。

If you construct your vector with a size, ie std::vector V(2), the vector won;t have to resize and your pointer will keep pointing to the value of a1. 如果构造一个具有大小的向量,即std :: vector V(2),则向量将不必调整大小,并且指针将始终指向a1的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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