转换为 void* 并返回 Original_Data_Type*
我多次看到并使用了C++,特别是在各种线程实现中.我想知道这样做是否有任何陷阱/问题?当我们强制转换为 void* 并再次返回时,有什么方法可能会遇到错误或未定义的条件吗?如果有这些问题,我们应该如何解决?
I have seen and used this many times is C++, specially in various thread implementations. What I wonder is if there are any pitfalls/ issues of doing this? Is there any way that we could run in to an error or undefined condition when we are casting to void* and back again? How should we resolve such issues if there are any?
谢谢.
推荐答案
我想知道这样做是否有任何陷阱/问题?
在将 void*
转换回特定类型时,您需要绝对确定,否则,您最终会遇到 未定义行为 和潜在的灾难.一旦你使用void *
,你就会失去类型安全.很难跟踪void *
的类型实际上是指向,无法保证或确定它确实指向您要将其类型转换回的类型.
You need to be absolutely sure while casting the the void*
back to the particular type, if you don't, you end up with an Undefined behavior and a potential disaster. Once you use void *
you lose type safety.It is difficult to keep track of what type a void *
is actually pointing to, there is no way to guarantee or determine that it indeed points to the type to which you are going to typecast it back to.
当我们转换为 void* 并再次返回时,有没有什么方法可能会遇到错误或未定义的情况?
是的,#1
中提到的场景.
如果有这些问题,我们应该如何解决?
在 C++ 中完全避免使用 void *
,而是使用模板和继承.
在 C 中,您可能在某些情况下绝对需要它,但尽量减少它的使用.
底线,
C/C++ 允许你用脚射击自己,这取决于你做或不做.
Avoid using void *
in C++ completely, instead use templates and inheritance.
In C you might absoultely need it in certain situations but try to keep its use to a minimum.
Bottomline,
C/C++ allows you to shoot yourself in foot, it is up to you to do or not do so.
相关文章