C++取消引用void指针,将int ptr转换为void ptr

Shi*_*ked 2 c++ pointers void

这些代码行显示如下错误:

int e = 5, * ePtr = &e;
void * vPtr = ePtr; 
cout << *vPtr; 
Run Code Online (Sandbox Code Playgroud)

语法错误:

`void*'不是指向对象的类型

我知道:

  1. 任何指针类型都可以存储在void指针类型中而无需显式转换
  2. 解除引用尝试void指针是语法错误

但如果我们不能做#2点,除了语法正确之外,点#1的用途是什么?我想打印5(即e这里)使用vPtr..可能吗?

这很好用:

int e = 5, * ePtr = &e;
void * vPtr = ePtr; //specific to generic Ok!
double * dPtr = (double *)vPtr; //to let compiler know stoarge size
cout << *dPtr; //indirectly it is vPtr i.e. a void ptr, can be deref only if cast
Run Code Online (Sandbox Code Playgroud)

Mat*_*get 5

要使用void*指针,需要将指针强制转换为兼容类型.

void* 指针经常在C中使用,但是,因为在C++中我们可以执行函数重载和多态,它们的使用更加有限.

void*在C中使用指针的一个很好的例子是使用回调的函数:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 
                   void *(*start_routine) (void *), void *arg);
Run Code Online (Sandbox Code Playgroud)

当你调用pthread_create函数时,它会调用你的函数start_routine.在这种情况下,您可能希望将一些数据传递给您start_routine.由于线程库无法为您可能想要传递给回调的每种类型声明pthread_create函数,因此void*使用该类型.

void myCallBack(void* arg) {
   int* value = (int*)arg;

   /* Do something with value: it is an int* now*/
   printf("Message from callback %d\n", *value);
}


/* Some main function or whatever... */
{ 
  /*  ... */
  int foo = 123;
  ret = pthread_create(&thread, &attr,myCallBack, &foo);

  /*  ... */
}
Run Code Online (Sandbox Code Playgroud)