Tuesday, 15 January 2013

c++ - Explict Converversion of Smart Pointer to raw pointer of pointee type. -



c++ - Explict Converversion of Smart Pointer to raw pointer of pointee type. -

sorry, if basic question, trying run next program, , getting segmentation fault.

what understand?

there function proc(t) in t conerted t* means of operator t . hence while executing proc(t) function, have pointer type t, , legal invoke display () function.

what want ?

1) committing mistake?.

2) understanding correct?

#include <iostream> using namespace std; template <typename t> class sptr { private: t * __pointee; public: operator t * () { cout <<"inside t* () "<<endl; }; 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 proc (jtest * tmp) { cout <<" proc"<<endl; tmp->display (); cout <<"invoking jtest -> display "<<endl; } int main ( int argc, char ** argv) { sptr <jtest> t(new jtest); t->display(); proc(t); // invokes operator t*(). }

your operator t*() missing homecoming statement, apparently returns garbage value (a pointer random place in memory), , dereferencing pointer segfaults.

how come compiler didn't error out on beyond me.

c++

No comments:

Post a Comment