将类指针指向空指针 [英] Casting Class Pointer to Void Pointer

查看:164
本文介绍了将类指针指向空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何能够将一个类指针转换为一个通用指针,如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!

这篇关于将类指针指向空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆