当对象超出范围时,C ++是否会调用析构函数?

时间:2018-04-05 12:37:41

标签: c++ scope stack destructor

我想是的,但是

#include <iostream>

struct S {
    int t;
};

class C {
private:
    S s;
public:
    C() {s.t = 7;}
    ~C(){std::cout << "bye C" << std::endl;}
};

class D {
private:
    S s;
public:
    D(int t) {s.t = t;}
    ~D() {std::cout << "bye D(" << s.t << ")" << std::endl;}
};

int main() {
    C c0();
    C* c1 = new C();
    D d0();
    D d1(42);
    std::cout << __LINE__ << std::endl;
    delete c1;
    std::cout << __LINE__ << std::endl;
}

只打印(https://ideone.com/95DK9E

28
bye C
30
bye D(42)

那么为什么c0d0没有通过调用它们的析构函数来正确销毁呢?

1 个答案:

答案 0 :(得分:1)

c0d0不是对象。你已经写了两个函数声明。