[英]How to retype from (void *) to int in C++ without getting any warning when compiling with pedantic flag?
我有通过sockets
通信的mutlithread
客户端-服务器应用程序。 我用这种构造创建新线程:
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);
发送一些消息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函数中,这也不正确。
从int
为void*
,然后再转换为int
是一个非常糟糕的主意,因为C ++标准中绝对不能保证这两种类型的大小相同。
如果确实必须在整数类型和指针之间进行uintptr_t
(这不是一个好主意,但有时别无选择),请使用intptr_t
或uintptr_t
而不是int
因为可以保证它们的大小与指针相同。 这样,您将不会收到任何警告。
顺便提一句,由于您无法确定它们在static_cast
正在做什么(可能是static_cast
或reinterpret_cast
,谁知道?),因此像C ++这样的传统C转换在C ++中就被皱眉了。 最好使用适当的C ++强制转换,在您的情况下为reinterpret_cast
。
您可以添加诸如static_assert(sizeof(fd) <= sizeof(void*), "problem")
,并依赖于您的实现文档,reinterpret_cast将在这种情况下往返。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.