What are the reasons for casting a void pointer?

后端 未结 3 1385
梦如初夏
梦如初夏 2021-01-18 06:41

I\'m learning C++ from scratch, and as such I don\'t have an expert understanding of C. In C++, you can\'t cast a void pointer to whatever, and I understand the reasons behi

相关标签:
3条回答
  • 2021-01-18 07:23

    What are the possible reasons for [casting a void * pointer in C]? Isn't this a giant hole in type safety?

    It's the only possible way to support polymorphism, aka generic programming. There's no other way to make, e.g., a generic hash table. Polymorphism in C is wildly unsafe, but it's the only polymorphism there is.

    Be glad that C++ has parametric polymorphism (one of the many functions of templates).

    0 讨论(0)
  • 2021-01-18 07:39

    One reason: if you use sort to sort an array of structs, and you have a comparison function for the two structs, you'll need to cast the void pointers to pointers to the structs to access members of the struct.

    0 讨论(0)
  • 2021-01-18 07:40

    You can cast a void* to another pointer in both languages. Perhaps you meant implicitly.

    It's very convenient in C to not have to be explicit about it. In C++ we have templates, so to write generic code there's no need for void* casting and whatnot. In C there is no choice. A generic container has to hold void* to objects, and it's much easier to repeatedly say mydata* d = node; then it is mydata* d = (mydata*)node;.

    So it's pretty much like you said. In C type safety in general didn't receive as much emphasis as it did in C++, especially when it came to void* because it was suppose to be a simple generic pointer to whatever. There's no need for that in C++, so better make it explicit when you're dealing with it.

    0 讨论(0)
提交回复
热议问题