3

我想知道我是否在以下使用了好的方法:

  • 我想构造一个父类(A类),这个类应该拥有给定“Foo”类的一个实例
  • 我希望父类拥有一个子类成员(B 类),并且该成员应该具有对父类的 foo 成员的引用。

下面的代码似乎有效,但我想知道我是否只是“幸运”编译器足够同情。

为了清楚起见,我在下面的评论中添加了评论和我的问题。

谢谢 !

struct Foo
{
  std::string mValue;
};

class B
{
public:
  B(const Foo & foo) : mFoo_External(foo) {}
private:
  const Foo & mFoo_External; //this is an external reference to the member 
                             //(coming from A)
};

class A
{
public:
  //Here is the big question 
  //Shall I use : 
  //  A(const Foo & foo) : mFoo(foo), mB(mFoo) {}  
  //  or the declaration below
  A(const Foo & foo) : mFoo(foo), mB(foo) {}
private:
  //According to my understanding, the declaration 
  //order here *will* be important
  //(and I feel this is ugly)
  const Foo  mFoo;
  B mB;
};



void MyTest()
{
  std::auto_ptr<Foo> foo(new Foo());
  foo->mValue = "Hello";
  A a( *foo);
  foo.release();

  //At this point (after foo.release()), "a" is still OK 
  //(i.e A.mB.mFooExternal is not broken, although foo is now invalid)
  //
  //This is under Visual Studio 2005 : 
  //was I lucky ? Or is it correct C++ ?
}
4

2 回答 2

6

不,这个坏了。您mB将持有对传递给A对象构造函数的任何内容的引用,而不是对mFoo. 相反,你应该说:

A(const Foo & foo) : mFoo(foo), mB(mFoo) { }

请注意,这mB是构造函数参数的副本,而不是引用,因此您的MyTest函数很好。

于 2011-10-12T21:38:02.410 回答
3

由于您希望您的B对象持有对父成员的引用,因此您必须mB使用mFoonot进行初始化foo

您是正确的,成员变量的顺序很重要,因为它决定了初始化的顺序。构造函数中初始化程序的顺序并不能确定它们被调用的顺序,这可能会让人感到惊讶!请参阅构造函数初始化列表评估顺序

于 2011-10-12T21:58:57.540 回答