C ++在构造函数初始化列表中获取类成员地址 [英] C++ Get class member address in constructor initialization list
问题描述
我遇到了内存冲突错误,我不知道它来自哪里. 我的问题是:我是否可以在构造函数初始化列表中获取类成员的地址,以便可以将其传递给需要对其进行引用的对象?
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 ?
例如:
class A
{
};
class ReferencesA
{
A * const pA;
ReferencesA( A * ptrA ) : pA( ptrA ) { }
};
class B
{
A a;
ReferencesA referencesA;
B() : referencesA( & a ) { }
};
构造函数初始化列表中的& 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.
谢谢.
推荐答案
class B
中基本成员的初始化顺序是a
,然后是referencesA
.那是因为它们在类声明中依次出现 . (如果有的话,它们在构造函数的初始化列表中出现的顺序无关紧要.)
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.)
因此,使用&a
初始化referencesA
是安全的,即使有点脆弱.对于您来说,&a
是默认构造的成员a
的地址.
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.
这篇关于C ++在构造函数初始化列表中获取类成员地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!