¿Por qué puedo acceder a las funciones de miembro incluso después de que se eliminó el objeto?
Soy nuevo en C ++ y de lo que aprendí hasta ahora, cuando se llama a eliminar en un puntero que apunta a algo creado en el montón, lo que apunta ese puntero se borra y la memoria se libera, ¿verdad?
Sin embargo, cuando probé esto en una clase simple:
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;
}
};
Estas son solo algunas pruebas estúpidas para ver cómo funciona la eliminación:
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;
}
Aquí está la salida:
$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
Entonces, mi pregunta es, ¿por qué todavía puedo llamar a Go_XXX_Your_Self () e Identify_Your_Self () incluso después de que se eliminó el objeto?
¿Es así como funciona en C ++? (¿Hay incluso después de que lo elimine?)
¿También puedes ver si está ahí? (Sé que teóricamente no es posible, pero tengo curiosidad por ver qué métodos hay por ahí)