我有以下代码:
class A
{
public:
int x = 6;
~A() { std::cout << "\ndestr invoked\n"; }
};
int main()
{
int* x;
{
A a;
std::cout << &a.x << "\n";
x = &a.x;
}
std::cout << x << ": " << *x;
}
输出:
0x78cac859fc00
destr invoked
0x78cac859fc00: 6
如果我理解正确,似乎析构函数是自动调用的,但内存中的变量仍然存在。有人知道为什么吗?
在以下示例中(使用了指针,因此手动删除了对象):
class A
{
public:
int x = 6;
~A() { std::cout << "\ndestr invoked\n"; }
};
int main()
{
int* x;
{
A* a = new A;
std::cout << &a->x << "\n";
x = &a->x;
delete a;
}
std::cout << x << ": " << *x;
}
已清除变量:
Output:
0x1381360
destr invoked
0x1381360: 0
有人知道有什么区别吗?