Are members in a c++ class guaranteed be contiguous?

这一生的挚爱 提交于 2021-02-08 06:33:47

问题


Are class members in c++ guaranteed to be contiguous?

I've tried running the following code with almost all popular c++ compilers, and all of them yield the result 4, which is the relative address of the variable y. Is that a coincidence, or is it guaranteed by the language specifications to be this way? Isn't it possible that the compiler will not make the members x and y contiguous with the class basic address/ contiguous with each other?

Please note that this thread does not answer this question.

#include <iostream>

using namespace std;

class A {
public:

    void f(){
        cout << &(this->y) << endl;
    }

    int x, y;
};


int main(int argc, const char* argv[])
{
    A *a = 0;
    a->f();

    return 0;
}

回答1:


Because your class is not a polymorphic type, has no base class, and all the members are public, the address of x is guaranteed to be the address of the class.

Also, the address of y is guaranteed to be after the address of x, although there could be an arbitrary amount of padding between them. So yes, your result is a coincidence.

If your class is polymorphic, i.e. has a virtual function somewhere in either it or a base class, or the members are protected or private, then all bets are off.

So in your case, (void*)&(this->x) is (void*)this, and the address of this->y must be higher than the address of this->x.

Finally if you need the class members to be contiguous, and mutually reachable by pointer arithmetic, use

int x[2];

instead as the member.



来源:https://stackoverflow.com/questions/48300491/are-members-in-a-c-class-guaranteed-be-contiguous

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!