A brief analysis of the small role of void* in C++

  • 2020-05-27 06:49:54
  • OfStack

This article mainly gives you to share about C++ in void* 1 some you may not understand the small role, to share out for your reference to learn, the following words do not say, to 1 look at the detailed introduction.

Let's start with a piece of code:

#include <iostream> 
#include <string> 
using namespace std; 
void o(int* x, void* y){ 
 cout << *x << endl; 
 cout << x << endl; 
 cout << *(int*)y << endl; 
 cout << (int*)y << endl; 
int main() 
 int a = 1, b = 2; 
 o(&a, &b); 

The function o passes in two addresses, one is a and the other is b. Let's take a look at the output first:


First, the simplest, *x is the value, so it prints 1, and then x is the value & a, which is the memory address of a, so we can see that one address is output. These are the basics. They're simple.

The tricky part is that the void* pointer can be used instead of a pointer of any type, but when it comes to output or invocation, you explicitly cast the pointer and tell the compiler exactly what it is.

So let's look at the fourth, the fourth (int *) y equivalent tells the compiler that is one of type integer pointer, so the output the address, what about the third, plus * is value, but here to remember, don't write int * * y, because there is no * y (before the uncertain type such complains) so it must be noted.

This pass-through method can be used for pointer pass-through of indefinable types, but is slightly less efficient due to the type casting required for later parsing, so be careful if you make a large call.


Related articles: