How a vector allocates memory

Hii I know that a vector allocates continuous fixed memory when it needs to push_back some elements. And if he can not fit into it, he will alllocate the new memory and copy the old values ​​into it and delete the old memory. If so, the following code works

#include<iostream>  
#include<vector>  
using namespace std;   

class Test   
{
public :   
    int val;   
    Test()   
    {
        val=0;   
    }   
};   


int main()   
{
    vector<Test>vec;   
    Test t[10];   
    for (int i=0;i<5;i++)   
        vec.push_back(t[i]);   
    cout<<vec.capacity()<<endl; //printing 8   
    Test* obj=&vec[2];   
    obj->val=2;   
    cout<<obj<<endl;   
    for (int i=0;i<5;i++) //Adding 5 elements more 
        vec.push_back(t[i]);   
    Test* obk=&vec[2];    
    cout<<obk->val<<endl;    
    cout<<obj->val<<endl;    
    cout<<obj<<endl;  
    cout<<obk<<endl;  
}  

Here, if you see that obj accepts the vec [2] pointer, whose value on my machine comes 0x8bcb048. Then I insert 5 more elements, so the vector will allocate new memory. Now, if I take obk from the vector [2] its next address is 0x8bcb070. But if I try to persuade me using obj, this will not give any problem. Any reason?

+3
source share
4 answers

obj, . ?

undefined - , , - ( - ).

"". , , , , , . -, . segfault.

- , , .

+6

, , , , . undefined, "-, ".

, . , :

class Test;

std::set<Test*> valid_Test_objects;

class Test
{
    int val;

public:

    Test() : val(0)
    {
        valid_Test_objects.insert(this);
        std::cout << "constructed Test object @ " << this << std::endl;
    }

    Test(const Test& that) : val(that.val)
    {
        std::cout << "constructed Test object @ " << this << std::endl;
        valid_Test_objects.insert(this);
    }

    ~Test()
    {
        std::cout << "destructing Test object @ " << this << std::endl;
        valid_Test_objects.erase(this);
    }

    int value()
    {
        std::cout << "  accessing Test object @ " << this << std::endl;
        if (valid_Test_objects.find(this) == valid_Test_objects.end())
        {
            abort();
        }
        return val;
    }
};

int main()
{
    std::vector<Test> vec;
    vec.reserve(3);

    Test x;
    vec.push_back(x);
    Test* p = &vec[0];
    std::cout << p->value() << std::endl;

    std::vector<Test>::size_type cap = vec.capacity();
    while (cap == vec.capacity()) vec.push_back(x);

    std::cout << p->value() << std::endl;
}

, p->value(), p . undefined, -)

+4

. , , - / ( , )/ . .

:

  • .

  • (k ( , k = 2) )

  • old = current; current = new; { }

  • .

, reset. , , . , , , .

+4

, "obj", , Release . obj , , & vec [2], , . , , , .

+1

Source: https://habr.com/ru/post/1752951/


All Articles