简体   繁体   中英

Memory layout of a vector of classes containing a vector of data

Given the following simplified code:

class A
{
public:   
    std::vector<int> v;
    int i;
}

int main()
{
   std::vector<A> v;
   v.push_back(A());
   v.push_back(A());
   v.push_back(A());
   v.push_back(A());
   v.push_back(A());
   v.push_back(A());
   v.push_back(A());
   v[5].v.push_back(15);
}

Where is the member vector stored in relation to its other members. Does pushing back something into the member vector causes the vector of classes to reshuffle? Or is the memory for the vector stored elsewhere and the class just contains a reference to it? (I guess this answer)

The memory for the vector is stored elsewhere. Adding and removing elements from the vector has no effect on the sizeof or the structure of A .

A std vector has its header allocated on the stack when you write

std::vector<A> v;

but uses free store (ie heap memory) when allocating memory for the elements. Thus it has no effect on A's size.

When talking about the vector member of the class, its header is allocated where the class object is allocated (on the free store in the above case). And the rest holds.

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