强制转换为void *并返回Original_Data_Type * [英] Casting to void* and Back to Original_Data_Type*

查看:140
本文介绍了强制转换为void *并返回Original_Data_Type *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到和使用了很多次是C ++,特别是在各种线程实现。我不知道是否有任何陷阱/问题这样做?有没有办法,我们可以运行到一个错误或未定义的条件,当我们转换为void *,然后再回来?如果有任何问题,我们应该如何解决这些问题?



谢谢。

解决方案



$ b $ b

在将 void * 转换回特定类型时,您需要绝对确定,如果不这样,则最终得到未定义行为和潜在灾难。一旦您使用 void * ,您将失去 类型安全 。很难记住 void * 实际上是指向,没有办法保证或确定它确实指向您要将其重新键入的类型。


当我们转换为void *并返回时,是否有任何方法可以运行到错误或未定义的条件? p>

是,#1 中提及的方案。


如果有任何问题,我们应如何解决?


避免在C ++中使用 void * ,而是使用模板和继承。

在C中,您可能在某些情况下需要它但尝试将其使用限制在最低限度。

底线,

C / C ++允许您用脚射击自己,这取决于您是否要这样做。 / p>

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?

Thank you.

解决方案

What I wonder is if there are any pitfalls/ issues of doing this?

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.

Is there any way that we could run in to an error or undefined condition when we are casting to void* and back again?

Yes, the scenario mentioned in #1.

How should we resolve such issues if there are any?

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.

这篇关于强制转换为void *并返回Original_Data_Type *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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