我有兩個班,Base和Derived。Derived使用其自己的成員物件構造Base,該成員物件繼承自Base::BaseChild.
struct Base
{
struct BaseChild
{
int x = 5;
};
Base(BaseChild& c): baseData(c), constantVar(c.x)
{
assert(constantVar == 5);
}
int getX() const {return baseData.x;}
private:
const int constantVar;
BaseChild& baseData;
};
struct Derived: public Base
{
struct DerivedChild: public BaseChild
{
double y = 4.0;
};
Derived(): Base(data) {}
private:
DerivedChild data;
};
Derived myObject;
assert(myObject.getX() == 5);
推理:我這樣做是因為一切似乎都非常適合我的情況,我需要發送 Childs 與其他 Childs 交換他們的內容(vector、、、 ) shared_ptr,unique_ptr保留子記憶體地址,并且我仍然可以從 base 訪問 Child 物件類不需要虛函式,這會扼殺我的應用程式性能。
Question: I've read another post like this one, where it states initialization of a Derived member before the Base isn't possible. So the constantVar assert would always fail. However getX() works fine, after the constructor, and I'm interested in these functions which are called once the constructor ends. Is this safe? Or is there any hidden danger here?
uj5u.com熱心網友回復:
的基類Base在Derivedmember 之前構造data。
因此data,當您將對它的參考傳遞給Base的建構式時,它不會被初始化。初始化將在該建構式呼叫之后發生。
但是,您正在嘗試讀取in的建構式的x成員。此時的生命周期尚未開始,并且在其生命周期之外訪問物件的非靜態資料成員的值會導致未定義的行為。dataBasedata
斷言是否成功并不重要。未定義的行為允許任何一種結果。
如果您不嘗試訪問datainsideBase的建構式的值,而僅存盤對它的參考,則情況可能會有所不同(盡管在技術上不是標準中的規則)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/453135.html
標籤:c inheritance initialization member
上一篇:Sed命令僅在所需位置更改字串
下一篇:創建沒有其建構式引數的類變數
