我如何能够将一个类指针转换为一个通用指针,如void *?这个代码有效吗?
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指针转换
§4.10 Pointer conversions
2指向 cv T 的类型的右值,其中 T 是一个对象类型,可以转换为指向 cv 类型的右值 void 。将指向 cv T 的指针转换为指针到 cv void 指向类型为 T 的对象所在的存储位置的开始,是类型 T (即不是基类子对象)的最导出的对象(1.8)。
2 An rvalue of type "pointer to cv T," where T is an object type, can be converted to an rvalue of type "pointer to cv void." The result of converting a "pointer to cv T" to a "pointer to cv void" points to the start of the storage location where the object of type T resides, as if the object is a most derived object (1.8) of type T (that is, not a base class subobject).
这意味着您可以将指针转换为void指针。 ...
which means you can convert your pointer to class to a void pointer. And ...
§5.2.9静态投放
§5.2.9 Static cast
10可以显式地将转换为指向对象类型的指针的类型指向 cv void 将类型指针的值转换为指向 cv void 并返回原始指针类型将具有其原始值。
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 cv void" and back to the original pointer type will have its original value.
这意味着您可以使用 static_cast 将一个void指针转换回一个原始类指针。
which means you can use static_cast to convert a void pointer back to an original class pointer.
希望它有帮助。祝你好运!
Hope it helps. Good Luck!
更多推荐
将类指针指向空指针
发布评论