简体   繁体   中英

Array vs vector, memory layout

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 )?

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 lements in the std::vector<int> a, b will be allocated from the heap. Content of a and b is 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 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.

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