c++ - Seg fault trying to access an object member -


trying follow example showed in article http://goo.gl/dvglyv i've designed following class:

bridge.h :

class bridge { public:     ifframesender *pfrmsender;     std::string sendername;     ...     bridge(cfg_settings cfg_sett);     void saveframe(cv::mat &cvfrm, uint xoff, uint yoff);     ... } 

in particular pfrmsender pointer virtual class, ifframesender.

in bridge.cpp i've defined constructor:

bridge::bridge(cfg_settings cfg_sett) {     ...     /* instantiates sender_by_socket object using factory */     ifframesender *pfrmsender = framesenderfactory::get()->createframesender("framesenderbysocket");      ... } 

and method:

void bridge::saveframe(cv::mat &cvfrm, uint xoff, uint yoff) {     ...     pfrmsender->sendframe(...);     ... } 

well, seg fault when try invoke pfrmsender. i've done little of debug , i've discovered in bridge::saveframe method member has incorrect memory address (cccccccc) while in constructor it's correctly instatiated, i've printed memory address , seems consistent.

i've declared member in header file, supposed visible method of bridge class. wrong?

thanks in advance.

the problem :

bridge::bridge(cfg_settings cfg_sett) {    /* following temporary variable, destroyed after ctor returns */   ifframesender *pfrmsender = framesenderfactory::get()->createframesender("framesenderbysocket");  } 

you creating new (temporary) ifframesender * in constructor, destroyed once constructor returns. instead, initialize 1 declared class member:

bridge::bridge(cfg_settings cfg_sett) {   this->pfrmsender = framesenderfactory::get()->createframesender("framesenderbysocket");  } 

also better practice check null when using pointer:

void bridge::saveframe(cv::mat &cvfrm, uint xoff, uint yoff){     if(pfrmsender!=nullptr)        pfrmsender->sendframe(...);  } 

although, guess in case if pfrmsender can not constructed, bridge::bridge() may throw exception if creating meaningless.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -