我是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 + +? (有刪除後有嗎?)
也可以檢查,看看它不存在嗎? (我知道理論上是不可能的,但我很好奇,看看有什麼方法)
你只是在操作系統和贏得比賽......你最終會輸。 – Andy
注意'0x3e3eb0'的對象是如何從'200'變爲'4079280'的。 –
因爲未定義的行爲是一個無情的丫頭。遲早,她會打破你的。 – WhozCraig