C++ Get class member address in constructor initialization list

蓝咒 提交于 2019-12-12 18:38:50

问题


I'm having a memory violation error and I don't know where it comes from. My question is : am I allowed to get the address of a class member while inside the constructor initialization list so that I can pass it to an object that needs a reference to it ?

For example :

class A
{
};

class ReferencesA
{
    A * const pA;

    ReferencesA( A * ptrA ) : pA( ptrA ) { }
};

class B
{
    A a;

    ReferencesA referencesA;

    B() : referencesA( & a ) { }
};

Is is safe to & a inside the constructor initialization list ? It seems to me that it would be, but things don't always work like we expect.

Thank you.


回答1:


The order of the initialisation of the base members in class B is a, then referencesA. That's because they appear in that order in the class declaration. (The order in which they appear, if at all, in the initialisation list in your constructor is not relevant.)

So using &a to initialise referencesA is safe, if a little brittle. In your case, &a is the address of the default-constructed member a.

I'd advise against coding like this in case someone changes the order of the members in your class.



来源:https://stackoverflow.com/questions/33503206/c-get-class-member-address-in-constructor-initialization-list

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