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

Why is void* considered unsafe in C++?

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

  • 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++ 中被认为是不安全的?

在 C 中提供 "generic" 函数或数据结构的标准方法是使用 void* 作为数据类型,这样任何分配的内存都可以放入其中。这具有允许将不同类型的数据放入同一容器中的不幸影响。在 C++ 中,这是通过提供 "templates" 来解决的,它在编译时创建函数的类型安全实例和 classes/structs,从而确保类型正确性。

Why is void* considered unsafe in C++?

因为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* 作为参数的 generic c 样式函数那样丢失。