简体   繁体   中英

reinterpret_cast on a char* pointer

I had to change the prototype of a function getData() which is basically a legacy source code. Upon changing it from returning a char* as shown below, I started getting compile errors due to static_cast .The question I have is , Is it safe to use reinterpret_cast , instead of static_cast ?

  class C1{

     public:

     //void *getData() {return data;} //Legacy implementation*
     char *getData() {return data;}  //My new implementation

     private:
       char data[100];
   };

   int main()
   {
       C1 myobj;   
       unsigned char* begin;

       begin=static_cast<unsigned char*>(myobj.getData());  *//<== This gives compile error.use reinterpret_cast ?*
       return 0;
   }

Is there a better solution than reinterpret_cast ?

You can static_cast from a void * to any pointer type, or between pointers to related types in the sense when one herites from the other.

reinterpret_cast is intended to be used between pointers to unrelated types. Is is equivalent to a static_cast from first type to void * followed with a static_cast from void * to second type. It T and U are unrelated types:

U *u = ...;
T *t;

t = reinterpret_cast<T *>(u);  /* strictly the same as would be
t = static_cast<T *>(static_cast<void *>(u));  */

It depends of what you want to accomplish. If you want to just use the bitwise representation of data , with each element interpreted as unsigned char , then reinterpret_cast is the way to go.

Your question doesn't give us enough details to figure out if it is "safe" in your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM