c++ - 在使用 pedantic 标志编译时,如何在 C++ 中从 (void *) 重新键入到 int 而不会收到任何警告?

标签 c++ gcc compilation

我有一个多线程 客户端-服务器应用程序,它通过套接字 进行通信。 我用这种结构创建新线程:

 pthread_t thread;
 pthread_create(&thread, NULL, c->sendMessage, (void *) fd);

其中 fd 是连接的 ID,c->sendMessage 是一个函数,在创建新线程后调用并处理该线程。在此函数中,我需要通过 send(int sockfd, const void *buf, size_t len, int flags);

发送一些消息

所以我这样得到sockfd:

void * Client::sendMessage(void *threadid) {
   int sockfd = (int) threadid;
   // some more code here and in the end I send the data via send(int sockfd, const void *buf, size_t len, int flags)
}

我使用 -pedantic 标志进行编译,大多数编译器(包括我的编译器)在编译期间不会抛出任何警告或错误。但是有些人在编译期间抛出一个错误,指出这种从 void *int 的重新键入是不安全的,并且可能导致 loose of precision。我知道,这不是一个好的解决方案,应该做得更干净。但我不知道怎么做。任何人都可以建议我任何干净的做法,如何将 ponter 重新键入 int 并避免在编译期间出现任何警告?

最佳答案

发送指针而不是整数有什么问题?将int转换为void*,或将void*转换为int,这不是标准的一致性解决方案。

pthread_create(&thread, NULL, c->sendMessage, new int(fd));

int* sockfd_ptr = (int*)threadid;
// some usage
delete sockfd_ptr;

任何指针都可以转换为 void*,因此它应该可以正常工作。不要忘记在程序的某些地方删除 threadid。 可能创建一些存储引用/指针的类会更好。

另外,我不明白,你如何将成员函数发送到C函数中,这也不正确。

关于c++ - 在使用 pedantic 标志编译时,如何在 C++ 中从 (void *) 重新键入到 int 而不会收到任何警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16983235/

相关文章:

c++ - 如何为 txt 文件中的每个名称创建一个整数?

struct - 无法在golang中包含多个文件

javascript - CoffeeScript : if . 。是..那么

c - else if 语法错误?谁能帮忙找一下

c++ - 在重载运算符中访问另一个类的数据成员

c++ - 使用 C/C++ 获取 HASP key (问题)

c++ - 使用虚拟继承时是否可以避免冗余的基类初始化?

c - 按值将数组传递给函数

c - Atmega8 中的星期几功能未按预期工作

用 clang 而不是 gcc 编译