C++ 无法理解析构函数调用

问题描述 投票:0回答:1

这个程序是用自定义类A设计的,当调用复制构造函数时输出1,当调用析构函数时输出0。我在程序中复制了两次,删除了两次,但析构函数被调用了3次。结果输出是11000,为什么会这样呢?

#include <iostream>
using namespace std;

class A {
public:
    float v;
    A() {v = 1.0;}
    A(A &a) {A::v = a.v; cout << "1";}
    ~A() { cout << "0";}
    float set(float v){
        A::v = v;
        return v;
    }
    float get(float v){
        return A::v;
    }
};

int main(){
    A a, *b = new A(a), *c = new A(*b); // output 110 (Not sure why the destructor is called in this line)
    c->get(b->get(a.set(1.0)));
    delete b; // output 0 
    delete c; // output 0
    return 0;
}

/* 我尝试注释掉代码行,并通过这样做缩小了对此行的额外析构函数调用的范围:

A a, *b = new A(a), *c = new A(*b);
但是我仍然不明白为什么这里调用析构函数。 */

c++ class namespaces destructor iostream
1个回答
0
投票

该行中没有调用析构函数。当

A a
被销毁时调用。通过用不同的值初始化成员来区分不同的对象时,您可以更好地了解发生的情况:

#include <iostream>


class A {
public:
    int v;
    A(int v) : v(v)  {}
    ~A() { std::cout << v;}
};

int main(){
    A a(1), *b = new A(2), *c = new A(3);
    delete b; 
    delete c; 
    std::cout << "bye \n";
    return 0;
}

输出为:

23bye 
1

delete b
打印
2
delete c
打印
3
std::cout << "bye \n"
打印
bye
,当
main
返回时,
a
也被销毁,打印
1

© www.soinside.com 2019 - 2024. All rights reserved.