segmentation fault - Destructor not working in C++ for anonymous object? -
my friend told me c++ allows phone call fellow member function if instance destroyed memory. write code below verify it, why value of a
can extracted after object destroyed? thought there segment fault.
#include <iostream> class foo{ public: foo(int = 0){ std::cout << "created" << std::endl; this->a = a; } ~foo(){ std::cout << "destroyed" << std::endl; } foo *f(){ std::cout << "a=" << << std::endl; homecoming this; } private: int a; }; foo *iwanttocallf(int i){ homecoming ((foo)i).f(); } int main(){ for(int = 0; < 3; i++) iwanttocallf(i)->f(); }
output macbook air:
created a=0 destroyed a=0 created a=1 destroyed a=1 created a=2 destroyed a=2
usually compilers implementing fellow member function phone call call regular c function first argument pointer object (gcc far know). if pointer pointing 1 destroyed object doesn't mean memory has been stored changed, might changed. undefined behavior in general. in case got value of maybe next time different compiler or different code crash. seek utilize placement new operator set value of 'a' = 0 in destructor... , follow memory object stored.
c++ segmentation-fault destructor
No comments:
Post a Comment