第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么C ++需要用戶提供的默認(rèn)構(gòu)造函數(shù)來默認(rèn)構(gòu)造const對象?

為什么C ++需要用戶提供的默認(rèn)構(gòu)造函數(shù)來默認(rèn)構(gòu)造const對象?

C++
幕布斯6054654 2019-10-17 13:11:14
C ++標(biāo)準(zhǔn)(第8.5節(jié))說:如果程序要求對const限定類型T的對象進(jìn)行默認(rèn)初始化,則T必須是具有用戶提供的默認(rèn)構(gòu)造函數(shù)的類類型。為什么?我想不出在這種情況下為什么需要用戶提供的構(gòu)造函數(shù)的任何原因。struct B{  B():x(42){}  int doSomeStuff() const{return x;}  int x;};struct A{  A(){}//other than "because the standard says so", why is this line required?  B b;//not required for this example, just to illustrate      //how this situation isn't totally useless};int main(){  const A a;}
查看完整描述

3 回答

?
aluckdog

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超7個贊

我純粹是猜測,但請考慮其他類型也有類似的限制:


int main()

{

    const int i; // invalid

}

因此,此規(guī)則不僅是一致的,而且(遞歸地)可以防止統(tǒng)一的const(子)對象:


struct X {

    int j;

};

struct A {

    int i;

    X x;

}


int main()

{

    const A a; // a.i and a.x.j in unitialized states!

}

至于問題的另一面(允許使用默認(rèn)構(gòu)造函數(shù)的類型),我認(rèn)為這樣的想法是,具有用戶提供的默認(rèn)構(gòu)造函數(shù)的類型在構(gòu)造后應(yīng)始終處于某種合理的狀態(tài)。請注意,這些規(guī)則適用于以下情況:


struct A {

    explicit

    A(int i): initialized(true), i(i) {} // valued constructor


    A(): initialized(false) {}


    bool initialized;

    int i;

};


const A a; // class invariant set up for the object

           // yet we didn't pay the cost of initializing a.i

然后,也許我們可以制定一條規(guī)則,例如“必須在用戶提供的默認(rèn)構(gòu)造函數(shù)中明智地初始化至少一個成員”,但這花了太多時間來防范Murphy。C ++在某些方面傾向于信任程序員。


查看完整回答
反對 回復(fù) 2019-10-17
  • 3 回答
  • 0 關(guān)注
  • 568 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號