我是 C++ 的新手,从到目前为止我学到的知识中,当您在指向堆上创建的东西的指针上调用 delete 时,该指针指向的任何内容都会被擦除并释放内存,对吗?
但是,当我在一个简单的类上尝试这个时:
class MyClass
{
int _Id;
public:
MyClass(int id) : _Id(id)
{
std::cout << "$Constructing the damn thing! " << _Id << std::endl;
}
~MyClass()
{
std::cout << "?Destructing the damn thing! " << _Id << std::endl;
}
void Go_XXX_Your_Self()
{
std::cout << "%OooooooooO NOOOOOO! " << _Id << std::endl;
delete this;
}
void Identify_Your_Self()
{
std::cout << "#Object number: " << _Id << " Located at: " << this << std::endl;
}
};
这些只是一些愚蠢的测试,看看 delete 是如何工作的:
int main()
{
MyClass* MC1 = new MyClass(100);
MyClass* MC2 = new MyClass(200);
MyClass* MC3 = MC2;
std::cout << MC1 << " " << MC2 << " " << MC3 << " " << std::endl;
MC1->Identify_Your_Self();
MC2->Identify_Your_Self();
MC3->Identify_Your_Self();
delete MC1;
MC1->Identify_Your_Self();
MC3->Go_XXX_Your_Self();
MC3->Identify_Your_Self();
delete MC2;
MC2->Identify_Your_Self();
MC2->Go_XXX_Your_Self();
MC2->Identify_Your_Self();
return 0;
}
这是输出:
$Constructing the damn thing! 100
$Constructing the damn thing! 200
0x3e3e90 0x3e3eb0 0x3e3eb0
#Object number: 100 Located at: 0x3e3e90
#Object number: 200 Located at: 0x3e3eb0
#Object number: 200 Located at: 0x3e3eb0
?Destructing the damn thing! 100
#Object number: 0 Located at: 0x3e3e90
%OooooooooO NOOOOOO! 200
?Destructing the damn thing! 200
#Object number: 4079248 Located at: 0x3e3eb0
?Destructing the damn thing! 4079248
#Object number: 4079280 Located at: 0x3e3eb0
%OooooooooO NOOOOOO! 4079280
?Destructing the damn thing! 4079280
#Object number: 4079280 Located at: 0x3e3eb0
所以,我的问题是,为什么即使在对象被删除后我仍然能够调用 Go_XXX_Your_Self() 和 identify_Your_Self() ?
这是它在 C++ 中的工作方式吗?(删除后还有吗?)
你也可以看看它是否不存在?(我知道理论上是不可能的,但我很想知道有什么方法)