为什么在C ++中将void *视为不安全? [英] Why is void* considered unsafe in C++?

查看:191
本文介绍了为什么在C ++中将void *视为不安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Bjarne Stroustrup C ++常见问题解答站点。我在哪里看到以下行。

I'm reading Bjarne Stroustrup C++ FAQ site. Where I saw following line.



  • 避免 void * (将它们保持在低位级功能和数据结构
    (如果确实需要它们,并向用户提供类型安全的接口,通常是
    模板)

  • avoid void* (keep them inside low-level functions and data structures if you really need them and present type safe interfaces, usually templates, to your users)

为什么 void * 在C ++中不安全?

Why is void* considered unsafe in C++?

推荐答案


为什么void *在C ++中被认为是不安全的?

Why is void* considered unsafe in C++?

void * 表示没有任何类型信息的内存地址。编译器无法知道该地址上的原始内存包含哪些数据类型结构。

Because void* represents a memory address without any type information. The compiler cannot know what data type structures are used what the raw memory contains at that address.

在那种情况下,程序员负责解密内存布局

In that case the programmer is in charge to do the deciphering of the memory layout themselves correctly, which is an error prone process, and the programmer need to know exactly what they are doing there.

从这个意义上说,你一直在做什么?引用(强调我的)

In that sense as it is said what you've been citing (emphasis mine)




  • 避免 void * (如果您确实需要它们,请将它们保留在低级函数和数据结构中,并向您的用户提供 类型安全的 接口,通常是模板)

  • avoid void* (keep them inside low-level functions and data structures if you really need them and present type safe interfaces, usually templates, to your users)


这是关于失去类型安全性 void *

上面引用:

首选使用c ++模板,因为原始类型信息永远不会得到使用 void * 作为参数,与通用 c样式函数一样丢失。

A template in c++ is preferred, because the original type information won't ever get lost as with generic c style functions using void* as parameter.

这篇关于为什么在C ++中将void *视为不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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