[英]C++ : const references and initialization order
我想知道我是否正在使用以下的好方法:
下面的代碼似乎有效,但我想知道我是否只是“幸運”編譯器足夠同情。
為清楚起見,我在下面的評論中添加了評論和我的問題。
謝謝 !
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
函數很好。
由於您希望B
對象保存對父成員的引用,因此必須使用mFoo
而不是foo
初始化mB
。
你是正確的,成員變量的順序很重要,因為它決定了初始化的順序。 令人驚訝的是,構造函數中初始值設定項的順序並不能確定它們的調用順序! 請參閱構造函數初始化列表評估順序 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.