Saturday, 15 March 2014

c++ - deleting smart pointer, but still could able to access the pointee? -



c++ - deleting smart pointer, but still could able to access the pointee? -

i have returned pointee type operator t*(), , invoked delete operator on smart pointer, , tried invoking fellow member function, , have not got run time error. how possible? or understanding wrong? kindly suggest.

#include <iostream> using namespace std; template <typename t> class sptr { private: t * pointee__; public: operator t * () { cout <<"inside t* () "<<endl; homecoming pointee__; }; explicit sptr ( t * t ) { pointee__ = t; }; t * operator->() { homecoming pointee__; } }; class jtest { private: int x; public: jtest ( int l=100) { x=l; }; void display (); }; void jtest::display() { cout <<"display api x "<<x<<endl; } void jfunc (jtest * tmp) { cout <<" jfunc"<<endl; tmp->display (); cout <<"invoking jtest -> display "<<endl; } int main ( int argc, char ** argv) { sptr <jtest> t(new jtest); t->display(); delete t; // invokes operator t* () , , dangerous!!!.. t->display (); }

output:

display api x 100 within t* () display api x 100

deleting t marks memory pointed t unused, leaves address stored in t intact. when seek utilize object stored @ t, c++ not check if has been deleted, while have crash, may work if memory used deleted object has not yet been overwritten system.

in short: work, crash, , bad idea.

if want protect yourself, set t null after have deleted it.

c++

No comments:

Post a Comment