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

标签 c++ pointers void

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

int e = 5, * ePtr = &e;
void * vPtr = ePtr; 
cout << *vPtr; 

语法错误:

`void*' is not a pointer-to-object type

我知道:

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

但是如果我们不能做到第 2 点,那么第 1 点除了在语法上正确之外还有什么用?我想使用 vPtr 打印 5(即 e)..这可能吗?

这很好用:

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

最佳答案

要引用 void* 指针,您需要将指针转换回兼容类型。

void* 指针在 C 中经常使用,但是,由于在 C++ 中我们可以进行函数重载和多态性,因此它们的使用受到更多限制。

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

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, 
                   void *(*start_routine) (void *), void *arg);

当您调用 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);

  /*  ... */
}

关于C++ 取消引用 void 指针,将 int ptr 转换为 void ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16830042/

相关文章:

c++ - 如何在 C++ 中使用位掩码?

c++ - 如何在 C++98 中实现作用域枚举并可以像 C++11 中的枚举类一样使用?

c - shm_内存 + mmap + 表 + 结构

C++/SDL 'void*' 不是点对对象类型

c++ - sizeof(void()) 是合法的表达式吗?

c++ - 在 C++ 全局运算符上 new : why it can be replaced

c++ - 从另一个线程恢复 asio 协程

C++ 多态性/指针 - 表达式必须具有常量值

c++ - 没有智能指针怎么处理指针?

c - 根据C中的定界符拆分字符串