[英]What’s the best way to cast a function pointer from one type to another?
[英]What is the best way to determine object pointer by pointer to one of it's members?
就像我有:
struct S
{
std::size_t szArray;
int dArray[];
} ;
int main()
{
extern int (*pArr)[]; //pointer to member 'dArray' of object with type 'S'
S *pStruct = /*??????????*/; //pointer to the object
}
获取此指针的最佳方法是什么?
没有做到这一点的好方法。
唯一受支持的方法是
#include <cstddef> // for offsetof
S *pStruct = reinterpret_cast<S*>
(reinterpret_cast<char*>(pArr) - offsetof(S, dArray));
请注意, offsetof
仅针对标准布局类型进行了明确定义,并且标准C ++不允许将未调整大小的数组用作类成员。 除非您有使用C习惯用法的充分理由,否则我建议std::vector<int>
会更安全,更方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.