2016-02-26 60 views
4

我在做練習,我不明白爲什麼下面的代碼返回:刪除C++行使

Program start, before f() -- number of objects: 0 
After f(), before g()  -- number of objects: 0 
After g(), before h()  -- number of objects: -1 
After h(), program end -- number of objects: -1 

沒有什麼錯F(),我明白了一切發生的事情。但是,我無法弄清楚在g()和h()中如何調用構造函數和析構函數。謝謝:)

代碼:

class Counted { 
public: 
    Counted(); 
    ~Counted(); 
    static int getNbrObj(); 
private: 
    static int nbrObj; 
}; 

int Counted::nbrObj = 0; 

Counted::Counted() { 
    nbrObj++; 
} 

Counted::~Counted() { 
    nbrObj--; 
} 

int Counted::getNbrObj() { 
    return nbrObj; 
} 

void f() { 
    Counted c; 
    Counted* pc = new Counted; 
    delete pc; 
} 

void g() { 
    Counted c1; 
    Counted c2 = c1; 
} 

void h() { 
    Counted c1; 
    Counted c2; 
    c2 = c1; 
} 

using namespace std; 

void print_nbr_objects(const string& msg) { 
    cout << msg << " -- number of objects: " 
     << Counted::getNbrObj() << endl; 
} 

int main() { 
    print_nbr_objects("Program start, before f()"); 
    f(); 

    print_nbr_objects("After f(), before g() "); 
    g(); 

    print_nbr_objects("After g(), before h() "); 
    h(); 

    print_nbr_objects("After h(), program end "); 
} 
+0

我想這是功課。爲什麼不使用調試器? –

回答

3

你剛纔儀器一個構造,但C++類有多個構造函數。特別是,你需要儀器拷貝構造函數,這是一個有類似的簽名如下:

Counted(Counted const& other); 

拷貝構造函數被調用至少一個語句代碼:

Counted c2 = c1; 
+0

有關其他參考,請參見[三規則](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-reeree)。 – Kupiakos

2

g() c2是用複製構造函數構造的(它沒有實現,所以它得到的默認編譯器生成一個),但通過您定義的析構函數銷燬。

1

在你的G功能,線路

Counted c1 = c1; 

調用不同的構造函數:拷貝構造函數。因爲這個構造函數不會增加nbrObj,所以當c1和c2解構時,它們會將nbrObj遞減兩次。

然而,你的g函數使用了默認的構造函數和解構器,所以對數字沒有影響。

0

添加一個拷貝構造函數,你會得到預期的結果:

class Counted { 
public: 
    Counted(); 
    Counted(const Counted& other) 
    { 
     nbrObj++; 
    } 
    ~Counted(); 
    static int getNbrObj(); 
private: 
    static int nbrObj; 
}; 

int Counted::nbrObj = 0; 

Counted::Counted() { 
    nbrObj++; 
} 

Counted::~Counted() { 
    nbrObj--; 
} 

int Counted::getNbrObj() { 
    return nbrObj; 
} 

void f() { 
    Counted c; 
    Counted* pc = new Counted; 
    delete pc; 
} 

void g() { 
    Counted c1; 
    Counted c2 = c1; 
} 

void h() { 
    Counted c1; 
    Counted c2; 
    c2 = c1; 
} 

using namespace std; 

void print_nbr_objects(const string& msg) { 
    cout << msg << " -- number of objects: " 
     << Counted::getNbrObj() << endl; 
} 

int main() { 
    print_nbr_objects("Program start, before f()"); 
    f(); 

    print_nbr_objects("After f(), before g() "); 
    g(); 

    print_nbr_objects("After g(), before h() "); 
    h(); 

    print_nbr_objects("After h(), program end "); 
}