简体   繁体   English

通过指向对象成员之一的指针确定对象指针的最佳方法是什么?

[英]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.

相关问题 将 function 指针从一种类型转换为另一种类型的最佳方法是什么? - What’s the best way to cast a function pointer from one type to another? 在C ++中将指针表示为字符串的最佳可移植方式是什么? - What's the best portable way to represent pointer as string in C++? 指针成员和成员函数的最佳用途是什么? - What's the best use you've had with pointer to members and member functions? 存储指向类对象的指针的最佳方法 - best way to store adresses of pointer to an object of class 如何复制包含指向其他几个成员之一的指针的对象? - How to copy object which contains a pointer to one of several other members? 如果将右值分配给该类的对象,该类的指针成员会怎样? - What happen to pointer members of a class if I assign a rvalue to an object of that? 在自定义 std::vector 类容器中处理指针和非指针模板类型的最佳方法是什么? - What's the best way to handle pointer & non-pointer template types in a custom std::vector-like container? 返回指针的最佳方法 - Best way of returning a pointer 当一次只需要其中一种类型时,保持指向不同类型的指针的最佳方法是什么? - What is the best way to keep a pointer to different types when only one of them is needed at a time? 返回指向向量数据的指针的最佳方法是什么? 常量还是非常量? - what is the best way to return a pointer to vector's data? const or non-const?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM