c++ - method on deleted instance of class still work? -
i have code on visual c++ 2010
#include <iostream> #include <string> using namespace std; class human { private: int magic; int health; string name; public: int getmagic() const; int gethealth() const; human(int, string); ~human(); }; //helper int human::gethealth() const { cout <<"this returns human::health" << endl; return human::health; } int human::getmagic() const { cout <<"this returns this->magic"<< endl; return this->magic; } //con/destructor human::human(int a, int b, string c): health(a), magic(b), name(c) { cout<<c<<" born!"<<endl; } human::~human() { cout <<this->name << " killed!" << endl; } int main (){ human lucife(20,10,"lucife"); cout << lucife.gethealth()<<endl; cout << lucife.getmagic()<<endl; lucife.~human(); cout << lucife.gethealth()<<endl; cout << lucife.getmagic()<<endl; cout<<endl; lucife.~human(); system("pause"); }
and when run it:
lucife born! returns human::health; 20 returns this->magic 10 lucife killed! returns human::health 20 returns this->magic 10 killed!
i have 3 questions:
- after killed instance "lucife" first time, why did 2 methods gethealth() , getmagic() still worked?
- the second time called ~human() on instance "lucife", why didn't print out "lucife killed!" first time? happened here? name value deleted?
- does return human::health , return this->health mean same thing? tried , see there no difference. think both of them return health of instance on method called ("lucife" in case).
many you
as @r , @rupesh mentioned, seeing behavior that's undefined.
however, if may provide little more explanation what's going on in specific code in specific environment, might it.
- after killed instance "lucife" first time, why did 2 methods gethealth() , getmagic() still worked?
first of all, not call object's destructor
explicitly that. automatically fired out of scope main
. that's never practice.
the reason can still invoke gethealth()
, getmagic()
functions first hidden argument this
.
you might surprised if see
class aaa { public: void f() { std::cout << "hello world" << std::endl; } } ((aaa*) 0)->f();
able compiled , running okay. (depending on environment).
so if invoked destructor explicitly in middle of scope hoping literally destruct inside, might still able reach this
without dereferencing nullptr
, give this
intended functions luck.
- the second time called ~human() on instance "lucife", why didn't print out "lucife killed!" first time? happened here? name value deleted?
it's because when human::~human()
fired, destructor of std::string
gets fired, ends tidying.
- does return human::health , return this->health mean same thing? tried , see there no difference. think both of them return health of instance on method called ("lucife" in case).
no, different. in code, human::health
converted this->health
because used inside class human
.
Comments
Post a Comment