我认为该标准为我提供了一个函数来查找结构的第一个st 元素。不过我好像找不到。
我害怕对齐:我认为将 reinterpret_cast
放入结构的第 1st 元素中是不合法的,对吗?
例如给定 struct { int first, int second } foo
;如果我不知道 first
被布置为 1<支持>st 元素? (这意味着 &foo.first
不是有效的解决方案。)
最佳答案
I don't think it's legal to reinterpret_cast into the 1st element of a struct is it?
它是合法的,但前提是该类是标准布局。标准草案:
[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 ...
关于c++ - 获取指向结构的第一个元素的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53836853/