[英]What is the best way to determine object pointer by pointer to one of it's members?
Like if I have: 就像我有:
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
}
What is the best way to get this pointer? 获取此指针的最佳方法是什么?
There's no good way to do that. 没有做到这一点的好方法。
The only supported way is 唯一受支持的方法是
#include <cstddef> // for offsetof
S *pStruct = reinterpret_cast<S*>
(reinterpret_cast<char*>(pArr) - offsetof(S, dArray));
Beware that offsetof
is only well-defined for standard-layout types, and that standard C++ doesn't allow unsized arrays as class members. 请注意, offsetof
仅针对标准布局类型进行了明确定义,并且标准C ++不允许将未调整大小的数组用作类成员。 Unless you've got a good reason for using C idioms, I'd suggest that std::vector<int>
would be safer and more convenient. 除非您有使用C习惯用法的充分理由,否则我建议std::vector<int>
会更安全,更方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.