How can I able to cast a class pointer to a generic pointer like void*? Like is this code valid?,
class CFoo
{
int a;
public:
CFoo():a(1){}
~CFoo(){}
getNum(){return a;}
};
void tfunc(void* data)
{
CFoo* foo = static_cast<CFoo*>(data);
std::cout << "Number: " << foo->getNum();
delete foo;
}
int main()
{
CFoo* foo = new CFoo;
void* dt = static_cast<void*>(foo);
tfunc(dt); // or tfunc(static_cast<void*>(food));
return 0;
}
This is perfectly valid. Here is what standard has to say about it:
§4.10 Pointer conversions
2 An rvalue of type "pointer to cv
T
," whereT
is an object type, can be converted to an rvalue of type "pointer to cvvoid
." The result of converting a "pointer to cvT
" to a "pointer to cvvoid
" points to the start of the storage location where the object of typeT
resides, as if the object is a most derived object (1.8) of typeT
(that is, not a base class subobject).
which means you can convert your pointer to class to a void pointer. And ...
§5.2.9 Static cast
10 An rvalue of type "pointer to cv
void
" can be explicitly converted to a pointer to object type. A value of type pointer to object converted to "pointer to cvvoid
" and back to the original pointer type will have its original value.
which means you can use static_cast
to convert a void pointer back to an original class pointer.
Hope it helps. Good Luck!
In C++ you don't need the static cast to get to void*
:
int main()
{
CFoo* foo = new CFoo;
void* dt = foo;
tfunc(dt); // or tfunc(foo);
return 0;
}
NB: your implementation of tfunc()
is quite correct in that it does need the cast.
Is this valid?
Yes, it is valid as per standard § 5.2.9.7
A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T,” where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. The null pointer value is converted to the null pointer value of the destination type. A value of type pointer to object converted to “pointer to cv void” and back, possibly with different cv-qualification, shall have its original value. [ Example:
T* p1 = new T;
const T* p2 = static_cast<const T*>(static_cast<void*>(p1));
bool b = p1 == p2; // b will have the value true.
CFoo* foo = new CFoo;
void* dt = (void*)foo;
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.