C++ : const references and initialization order

标签 c++ const-reference

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

  • 我想构造一个父类(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++ ?
}

最佳答案

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

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

请注意,mB 是构造函数参数的拷贝,而不是引用,因此您的 MyTest 函数没问题。

关于C++ : const references and initialization order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7746849/

相关文章:

c++ - g++: 警告:整数常量对于 ‘long’ 类型来说太大

c++ - 为什么 std::cin.clear() 在这个简单的程序中不起作用?

c++ - 临时 : No compiler warning? 的绑定(bind)常量&

c++ - C++ 临时对象的生命周期是在什么时候创建的? : expression extended by binding it to a local const reference?

c++ - 为什么我的 operator=(&&) 模板只绑定(bind)到 const 而不是 &&?

c++ - 构造对象时理解赋值中的const引用

c++ - 在中心而不是在一个顶点合并颜色顶点?

c++ - 什么是函数 __tcf_0? (在使用 gprof 和 g++ 时看到)

数据比较的C++警告