How to calculate offset of a class member at compile time?

前端 未结 4 1340
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 04:39

Given a class definition in C++

class A
{
  public:
    //methods definition
    ....

  private:
    int i;
    char *str;
    ....
}

Is i

4条回答
  •  感情败类
    2020-12-09 05:15

    No, not in general.

    The offsetof macro exists for POD (plain old data) structs, and it may be extended slightly with C++0x to standard layout structs (or other similar slight extensions). So for those restricted cases, you have a solution.

    C++ offers a lot of freedom to compiler writers. I don't know of any clause that would prevent some classes from having variable offsets to members of the class -- however, I'm not sure why a compiler would do that either. ;)

    Now, one approach to keep your code standards compliant, yet still have offsets, would be to stick your data into a POD (or some C++0x extension) sub-struct, on which offsetof will work, then work on that sub-struct instead of on the entire class. Or you could surrender standards compliance. The offset of your struct within your class wouldn't be known, but the offset of the member within the struct would be.

    An important question to ask is "why do I want this, and do I really have a good reason"?

提交回复
热议问题