簡體   English   中英

為什么析構函數調用比構造函數調用多

[英]Why is there more destructor calls than constructor calls

我正在測試以下代碼,令我困惑的是析構函數調用比構造函數調用多:

#include <iostream>

struct A {
    A() { std::cout << 1; }
    A(int) { std::cout << 7; }
    ~A() { std::cout << 5; }
};

struct B {
    B() { std::cout << 2; }
    B(int) { std::cout << 9; }
    ~B() {std::cout << 3;}
};

struct C {
    B b;
    A a1;
    A a2;
    C() : a1(3){
        b = 3;
        a2 = 7;
    }
};

int main(){
    C c;
    return 0;
}

output如下:

B()  A(int) A() B(int) ~B() A(int) ~A() ~A() ~A() ~B() 
 2     7     1    9      3     7     5    5    5    3

我的猜測是,在 b = 3 和 a2 = 7 行上,3 和 7 必須隱式轉換為 B 和 A,當它們被復制到 b 和 a2 時,它們會被銷毀。

這是正確的還是這里發生了其他事情?

您沒有記錄復制構造函數復制賦值運算符,例如:

struct A {
    A() { ... }
    A(int) { ... }
    A(const A&) { ... } // <-- add this
    ~A() { ... }
    A& operator=(const A&) { ...; return *this; } // <-- add this
};

struct B {
    B() { ... }
    B(int) { ... }
    B(const B&) { ... } // <-- add this
    ~B() { ... }
    B& operator=(const B&) { ...; return *this; } // <-- add this
};

但是,如果您實際計算所顯示的輸出,您將看到您正在看到匹配的構造函數和析構函數。 您有 3 個A構造函數調用和 3 個~A析構函數調用。 你有 2 B構造函數調用和 2 ~B析構函數調用。

B()         C::b
A(int)      C::a1
A()         C::a2
B(int)      temp
B=          temp -> C::b
~B()        temp
A(int)      temp
A=          temp -> C::a2
~A()        temp
~A()        C::a2
~A()        C::a1
~B()        C::b

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM