删除c ++练习

时间:2016-02-26 20:00:37

标签: 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   ");
}

4 个答案:

答案 0 :(得分:3)

您只使用了一个构造函数,但C ++类有多个构造函数。特别是,您需要检测复制构造函数,它具有如下签名:

Counted(Counted const& other);

在代码中至少调用一个语句来复制构造函数:

Counted c2 = c1;

答案 1 :(得分:2)

g()中,c2是用复制构造函数构造的(你没有实现它,因此它获得了默认编译器生成的一个)但是通过你定义的析构函数销毁了。

答案 2 :(得分:1)

在你的g函数中,行

Counted c1 = c1;

调用另一个构造函数:复制构造函数。因为这个构造函数不会增加nbrObj,所以当c1和c2都被解构时,它们会将nbrObj递减两次。

你的g函数使用默认构造函数和解构函数,因此对数字没有影响。

答案 3 :(得分: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   ");
}