Question

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)

Was it helpful?

Solution

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.

OTHER TIPS

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

std::vector<A> v;

but uses free store (i.e. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top