c++ - Casting Pointer of Stack Objects -


i'm building messaging queue , have 2 types of messages 1 uses template class.

class message { public:     message() : m_imessagetype( message_undefined ) {}     message( int imessagetype ) : m_imessagetype( imessagetype ) {}     int gettype() { return m_imessagetype; }     void settype( int imessagetype ) { m_imessagetype = imessagetype; } private:     int m_imessagetype; }  template<typename t> class datamessage: public message { public:     datamessage() : message(), m_odata( t() ) {}     datamessage( int imessagetype, t odata ) : message( imessagetype ), m_odata( odata ) {}     t getdata() { return m_odata; }     void setdata( t odata ) { m_odata = odata; } } 

which allows me send messages this

message tomessage( message_get_name ); datamessage<std::string> frommessage(); messenger::getmessenger()->sendmessage( &tomessage, &frommessage, consumer ); std::cout << "consumer name: " << frommessage.getdata() << std::endl; 

however, leads me doing type casting while handling messages internally (casting message appropriate datamessage<std::string> frommessage in above code). 1 of consumers might this:

class receiver { public:     receiver() { messenger::register( receiver, ); }     handlemessage( message* pin, message* pout ) {         // ignoring usual checking message type         (static_cast<datamessage<std::string>*>( pout ))->setdata( "consumer1" );     } 

is safe cast pointer if points object on stack of calling method?

if try following code (which wrong)

message tomessage( message_get_name ); message frommessage; // consumer going try , cast datamessage<std::string> messenger::getmessenger()->sendmessage( &tomessage, &frommessage, consumer ); 

i don't segfaults or errors. going horribly wrong , it'll creep later during execution?

you’re asking 2 questions here.

is safe cast pointer if points object on stack of calling method?

yes, safe. doesn’t matter object lives long it’s of type cast to.

however, design static_cast not style. dynamic_cast @ least return null pointer if object not of supplied type.

is going horribly wrong , it'll creep later during execution?

yes. casted message datamessage. that’s undefined behavior. possibly you’ll end reading whatever happens on stack after end of message object.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -