【发布时间】:2013-08-30 22:59:04
【问题描述】:
我是 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;
}
};
这些只是一些愚蠢的测试,看看删除是如何工作的:
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++ 中的工作方式吗? (删除后还有吗?)
您也可以检查一下它是否不存在吗? (我知道理论上是不可能的,但我很想知道有什么方法)
【问题讨论】:
-
你只是在与操作系统赛跑并赢了……你最终会输。
-
请注意
0x3e3eb0号码处的对象如何从200更改为4079280。 -
因为未定义的行为是个没心没肺的丫头。迟早,她会打破你的。
-
未定义行为!!!你的应用迟早会崩溃.. :)
-
不是完全重复,但它解释了您想知道的内容:stackoverflow.com/questions/6441218/…
标签: c++ function object member delete-operator