c+ - Quand devrait static_cast, dynamic_cast, const_cast and reinterpret_cast be used

Mots clés : c++pointerscastingc++-faqc++

meilleur 1 Réponses c+ - Quand devrait static_cast, dynamic_cast, const_cast and reinterpret_cast be used

vote vote

95

OnEventData(void* pData)  {   ......    //  pData is a void* pData,     //  EventData is a structure e.g.    //  typedef struct _EventData {   //  std::string id;   //  std:: string remote_id;   //  } EventData;    // On Some Situation a void pointer *pData   // has been static_casted as    // EventData* pointer     EventData *evtdata = static_cast<EventData*>(pData);   ..... } 
void DebugLog::OnMessage(Message *msg) {     static DebugMsgData *debug;     static XYZMsgData *xyz;      if(debug = dynamic_cast<DebugMsgData*>(msg->pdata)){         // debug message     }     else if(xyz = dynamic_cast<XYZMsgData*>(msg->pdata)){         // xyz message     }     else/* if( ... )*/{         // ...     } } 
// *Passwd declared as a const  const unsigned char *Passwd   // on some situation it require to remove its constness  const_cast<unsigned char*>(Passwd) 
typedef unsigned short uint16;  // Read Bytes returns that 2 bytes got read.   bool ByteBuffer::ReadUInt16(uint16& val) {   return ReadBytes(reinterpret_cast<char*>(&val), 2); } 

Questions similaires