Why is void* considered unsafe in C++? [duplicate]

天涯浪子 提交于 2019-12-07 16:13:46

问题


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

  • 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)

Why is void* considered unsafe in C++?


回答1:


Why is void* considered unsafe in C++?

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)

  • 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)

it is about loosing type safety with void*.


To add up about the cite above:

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.




回答2:


The standard way of providing "generic" functions or data structures in C is to use void* as the data type, so that any allocated memory could be put into it. This has the unfortunate effect of allowing putting different types of data into the same container. In C++, this is solved by providing "templates", which create type-safe instances of functions and classes/structs at compile time, thus ensuring type correctness.



来源:https://stackoverflow.com/questions/52125956/why-is-void-considered-unsafe-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!