簡體   English   中英

如何在使用pedantic標志進行編譯時,在沒有得到任何警告的情況下,在C ++中從(void *)重新鍵入int?

[英]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並避免在編譯過程中出現任何警告?

發送指針而不是整數有什么問題? 轉換intvoid* ,或void*int ,它不是標准的符合性解決方案。

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

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

任何指針都可以轉換為void* ,因此應該可以正常工作。 不要忘記在程序的某些位置刪除threadid 創建存儲引用/指針的類可能會更好。

另外,我不明白如何將成員函數發送到C函數中,這也不正確。

intvoid* ,然后再轉換為int是一個非常糟糕的主意,因為C ++標准中絕對不能保證這兩種類型的大小相同。

如果確實必須在整數類型和指針之間進行uintptr_t (這不是一個好主意,但有時別無選擇),請使用intptr_tuintptr_t而不是int因為可以保證它們的大小與指針相同。 這樣,您將不會收到任何警告。

順便提一句,由於您無法確定它們在static_cast正在做什么(可能是static_castreinterpret_cast ,誰知道?),因此像C ++這樣的傳統C轉換在C ++中就被皺眉了。 最好使用適當的C ++強制轉換,在您的情況下為reinterpret_cast

您可以添加諸如static_assert(sizeof(fd) <= sizeof(void*), "problem") ,並依賴於您的實現文檔,reinterpret_cast將在這種情況下往返。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM