获取指向结构的第一个元素的指针
Getting a Pointer to the First Element of a Struct
我认为标准为我提供了一个函数来查找结构的第 1st 个元素。不过我好像找不到。
我害怕对齐:我认为将 reinterpret_cast
放入结构的第 1st 元素中是不合法的,是吗?
因此,例如给定 struct { int first, int second } foo
;如果我不知道 first
被布局为 1[=21=,我将如何获得 foo
中 1st 元素的地址]st元素? (这意味着 &foo.first
不是有效的解决方案。)
I don't think it's legal to reinterpret_cast into the 1st element of a struct is it?
它是合法的,但前提是class是标准布局。标准草案:
[basic.compound]
Two objects a and b are pointer-interconvertible if:
...
- one is a standard-layout class object and the other is the first non-static data member of that object,
or, if the object has no non-static data members, any base class subobject of that object (10.3), or
...
If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a
pointer to one from a pointer to the other via a reinterpret_cast ...
我认为标准为我提供了一个函数来查找结构的第 1st 个元素。不过我好像找不到。
我害怕对齐:我认为将 reinterpret_cast
放入结构的第 1st 元素中是不合法的,是吗?
因此,例如给定 struct { int first, int second } foo
;如果我不知道 first
被布局为 1[=21=,我将如何获得 foo
中 1st 元素的地址]st元素? (这意味着 &foo.first
不是有效的解决方案。)
I don't think it's legal to reinterpret_cast into the 1st element of a struct is it?
它是合法的,但前提是class是标准布局。标准草案:
[basic.compound]
Two objects a and b are pointer-interconvertible if:
...
- one is a standard-layout class object and the other is the first non-static data member of that object, or, if the object has no non-static data members, any base class subobject of that object (10.3), or
...
If two objects are pointer-interconvertible, then they have the same address, and it is possible to obtain a pointer to one from a pointer to the other via a reinterpret_cast ...