C++ Get class member address in constructor initia

2019-08-08 08:11发布

问题:

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.