Reputation: 30615
Could somebody confirm the difference between:
class A{
public:
std::vector<int> a;
std::vector<int> b;
};
and
class B{
public:
std::array<int, 1000> a;
std::array<int, 1000> b;
};
Class A
the object contains two pointers to two randomly-allocated regions on the heap?
In contrast the second class the object would have continuous memory allocated (depending where the object was- stack or heap) for both arrays, which would be continuous. The arrays would be located next to each other (which would not be the case with class A
)?
Upvotes: 1
Views: 1601
Reputation: 129364
Each of the vector instances inside an instance of class A
will contain something along the lines of three pointers [or two pointers and a size_t
aka std::vector::size_type
, or one pointer and two size_t
]. Storage for elements in the std::vector<int> a, b
will be allocated from the heap. Content of a
and b
are far from guaranteed to be close to each other. Each element within a
and b
will be stored consecutively, so aside from the extra pointer dereference, for example, cache-locality will be very similar between the two solutions.
However, if you do something like
A x;
x.a.resize(1000);
x.b.resize(1000);
on a fresh heap, chances are that a
and b
are indeed not very far apart.
In an instance of B, there will be two arrays, each big enough for 1000 integers, potentially with some padding between them. The arrays will be next to each other, aside from padding.
Upvotes: 3