简体   繁体   中英

C++ typecast: cast a pointer from void pointer to class pointer

How to cast a pointer to void object to class object?

With a static_cast . Note that you must only do this if the pointer really does point to an object of the specified type; that is, the value of the pointer to void was taken from a pointer to such an object.

thing * p = whatever(); // pointer to object
void * pv = p;          // pointer to void
thing * p2 = static_cast<thing *>(pv); // pointer to the same object

If you find yourself needing to do this, you may want to rethink your design. You're giving up type safety, making it easy to write invalid code:

something_else * q = static_cast<something_else *>(pv);
q->do_something();  // BOOM! undefined behaviour.

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