I found no better way to formulate my question like this: Is the output below always true? is this portable?
struct Point
{
int x;
int y;
};
//...
std::vector<Point> points(3);
unsigned char* start = (unsigned char*)(&points[0]);
unsigned char* end = (unsigned char*)(&points[1]);
std::cout << "is this the same ? " << std::distance(start,end) == sizeof(Point);
What if instead of a vector
, points
were defined as a raw array? Is the output still always true?
Point *points = new Point[3]; // instead of std::vector<Point> points(3);
An array is a collection of same type of elements which are sheltered under a common name. The number of 8 bit bytes that each element occupies depends on the type of array. If type of array is 'char' then it means the array stores character elements.
If the array is a character array, then its elements will occupy 1 byte of memory each. If it is a float array then its elements will occupy 8 bytes of memory each.
The maximum allowable array size is 65,536 bytes (64K).
Arrays have a fixed length that is specified in the declaration of the array. In C, there is no built-in method to get the size of an array. A little effort is required to get the length of the array by utilizing the in-built methods or pointers in C.
For std::vector
, [vector.overview]/1 (N3337) says:
The elements of a vector are stored contiguously, meaning that if
v
is avector<T, Allocator>
whereT
is some type other thanbool
, then it obeys the identity&v[n] == &v[0] + n
for all0 <= n < v.size()
.
So yes, your program's behaviour is portable and well-defined.
For arrays, [dcl.array]/1 states:
An object of array type contains a contiguously allocated non-empty set of
N
subobjects of typeT
.
This is not quite so explicit as the vector
quote, but the co-usage of the word "contiguous" points to the fact that the std::vector
storage identity also applies to arrays.
Yes, one of the requirement for the vector is that its elements must be store contiguously.
From n2798:
23.2.6 Class template vector [vector]
1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With