C++ 类型转换:将指针从 void 指针转换为类指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10072004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:34:55  来源:igfitidea点击:

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

c++pointersvoid

提问by Naveen

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

如何将指向 void 对象的指针转换为类对象?

回答by Mike Seymour

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 voidwas taken from a pointer to such an object.

带有static_cast. 请注意,只有在指针确实指向指定类型的对象时才必须这样做;也就是说,指向的指针的值void取自指向此类对象的指针。

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.