Home > Software engineering >  Can I be sure a vector contains objects and not pointers to objects?
Can I be sure a vector contains objects and not pointers to objects?

Time:10-27

Can I be sure an std::vector (or, in general, any standard container) contains objects and not pointers to objects, no matter how complex the objects' class is, if it has constant size?

E.g.: in this simple case:

struct MyStruct { int a, b; };
std::vector<MyStruct> vs;

The resulting vector layout is:

[ ..., a1, b1, a2, b2, a3, b3, ... ]

Does the Standard guarantees the same happens in this (or more complex) case(s), where the size of the structure is supposed to be constant:

struct MyStruct2 { float f[10]; };
std::vector<MyStruct2> vs2;

With layout:

[ ..., f1[0], f1[1], ..., f1[9], f2[0], f2[1], ..., f2[9], ... ]

instead of:

[ ..., *pf1, *pf2, ... ]
pf1 = [ f1[0], f1[1], ..., f1[9] ]
pf2 = [ f2[0], f2[1], ..., f2[9] ]

CodePudding user response:

Since C 11 and onwards (C 03 nearly guarantees it), the data in a std::vector are contiguous with no gaps.

In particular if you have a pointer to an element in the std::vector, you can reach all other elements using pointer arithmetic.

Of course, pointer arithmetic works in sizeof units of your struct. And the struct itself may contain padding. The behaviour on attempting to reach a b, given a pointer to an a in your struct is undefined.

  • Related