c ++:数组中的类成员有多远(以字节为单位)?

use*_*183 8 c++ language-lawyer

我发现没有更好的方法可以像这样制定我的问题:下面的输出总是正确吗?这便携式吗?

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);
Run Code Online (Sandbox Code Playgroud)

如果不是a vector,points被定义为原始数组怎么办?输出仍然是真的吗?

Point *points = new Point[3]; // instead of std::vector<Point> points(3);
Run Code Online (Sandbox Code Playgroud)

Tar*_*ama 5

因为std::vector,[vector.overview]/1(N3337)说:

一个向量的元素被存储连续的,这意味着如果v是一个vector<T, Allocator>其中T一些类型比其它bool,那么它遵循身份&v[n] == &v[0] + n所有0 <= n < v.size().

所以是的,你的程序的行为是可移植的并且定义明确.

对于数组,[dcl.array]/1表示:

数组类型的对象包含连续分配的非空N类型的子对象T.

这与vector引用并不那么明确,但"连续"一词的共同使用指出了std::vector存储标识也适用于数组的事实.