C++ mechanism of constructing, deconstructing and pointer to class object -
C++ mechanism of constructing, deconstructing and pointer to class object -
#include <iostream> using namespace std; class { private: int m_i; friend int main(int argc, char const *argv[]); public: (int = 0):m_i(i){}; void display() { cout << m_i << endl; } int result() {return m_i;} }; void createa(a *pa) { pa = new a(1); } a* createa() { a(2); homecoming &a; } void createaonstack() { a(3); } int main(int argc, char const *argv[]) { a; * pa = &a; pa->display(); createa(pa); pa->display(); * a2 = createa(); cout << a2->m_i << endl; createaonstack(); cout << a2->m_i << endl; homecoming 0; }
the results of programme above is
0 0 2 3
how explain result 2 , 3? understanding, object created in function createa()
should deconstructed, , pointer returns should point null
, why a2->m_i
can 2. , 3 more confusing, seems function createaonstack()
has nil a2.
you said
from understanding, object created in function createa()
should deconstructed, , pointer returns should point null
, why a2->m_i
can 2
.
it true
the object created in function createa()
should deconstructed
it not true that
and pointer returns should point null
the pointer returned createa
non-null though invalid pointer utilize in calling function.
but why a2->m_i
can 2
.
it's pure coincidence. undefined behavior. can happen when dereference a2
.
c++
Comments
Post a Comment