c++ - Strange Pointer Behavior -
take following struct , class:
struct teststruct { }; class testclass { public: teststruct* teststruct; };
do following in main
:
testclass testclass; if (testclass.teststruct == null) cout << "it null." << endl; else cout << "it not null.";
the output be: it not null.
.
however, if instead this:
testclass testclass; if (testclass.teststruct == null) cout << "it null." << endl; else cout << "it not null." << endl << testclass.teststruct;
the output be: it null.
.
interestingly enough, if (fundamentally same above):
testclass testclass; if (testclass.teststruct == null) { cout << "it null." << endl; } else { cout << "it not null." << endl; cout << testclass.teststruct; }
the output be:
it not null. 0x7fffee043580.
what going on?
your pointer not initialized when declare testclass
. experience here undefined behaviour. value of pointer last value contain in memory section stored.
if wanted always null
, need initialize in constructor of class.
class testclass { public: testclass(): teststruct(null) {} teststruct* teststruct; };
Comments
Post a Comment