Dlaczego mogę uzyskać dostęp do funkcji członka nawet po usunięciu obiektu?
Jestem nowym użytkownikiem C ++ iz tego, czego do tej pory dowiedziałem się, gdy wywołujesz delete na wskaźniku, który wskazuje na coś utworzonego na stercie, cokolwiek jest wskazywane przez ten wskaźnik, zostaje wymazane, a pamięć zostaje zwolniona, prawda?
Jednak kiedy próbowałem tego na prostej klasie:
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;
}
};
To tylko niektóre głupie testy, aby zobaczyć, jak działa usuwanie:
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;
}
Oto wyjście:
$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
Więc moje pytanie brzmi: dlaczego wciąż mogę zadzwonić do Go_XXX_Your_Self () i Identify_Your_Self () nawet po usunięciu obiektu?
Czy tak działa w C ++? (czy jest nawet po usunięciu?)
Możesz również sprawdzić, czy go tam nie ma? (Wiem, że teoretycznie nie jest to możliwe, ale jestem ciekawy, jakie metody tam są)