gpt4 book ai didi

c++ - 获取指向结构的第一个元素的指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:04:06 24 4
gpt4 key购买 nike

我认为该标准为我提供了一个函数来查找结构的第一个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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com