亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

為什么C ++需要用戶提供的默認構造函數來默認構造const對象?

為什么C ++需要用戶提供的默認構造函數來默認構造const對象?

C++
幕布斯6054654 2019-10-17 13:11:14
C ++標準(第8.5節)說:如果程序要求對const限定類型T的對象進行默認初始化,則T必須是具有用戶提供的默認構造函數的類類型。為什么?我想不出在這種情況下為什么需要用戶提供的構造函數的任何原因。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貢獻1847條經驗 獲得超7個贊

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


int main()

{

    const int i; // invalid

}

因此,此規則不僅是一致的,而且(遞歸地)可以防止統一的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!

}

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


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

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


查看完整回答
反對 回復 2019-10-17
  • 3 回答
  • 0 關注
  • 567 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號