[英]Why can you cast a integer as a void pointer but can't with CString?
請注意,我引用的是工作代碼,我正在嘗試實現相同的方法,但使用的是CString
。
以下方法有效,將 integer 轉換為空指針:
void **pParam = new void*[2];
pParam[0] = reinterpret_cast<void*>(this);
pParam[1] = reinterpret_cast<void*>(iTrayNumber);
_beginthreadex(NULL, 0, &CInspectionDone::InspectionDoneThread, reinterpret_cast<void*>(pParam), 0, NULL);
而如果我對 CString 執行相同的操作,則會出現以下錯誤:
CString strTest = _T("Hello");
void **pParam = new void*[2];
pParam[0] = reinterpret_cast<void*>(this);
pParam[1] = reinterpret_cast<void*>(strTest);
錯誤:
1>d:\v4\apps\serialcomm.cpp(160) : error C2440: 'reinterpret_cast' : cannot convert from 'CString' to 'void *'
1> Conversion requires a constructor or user-defined-conversion operator, which can't be used by const_cast or reinterpret_cast
是因為從根本上說你不能對CString
做同樣的事情嗎? 我試着在 inte.net 上搜索,它說重新解釋轉換的 function 是將一種數據類型的指針轉換為另一種數據類型。 除非指針可能只是整數並且它被接受被強制轉換。
如果對此有任何解釋,我將不勝感激。 提前致謝。
reinterpret_cast
執行許多特定的轉換,所有這些僅在相當特殊的情況下才需要。 您在這里所做的事情不需要reinterpret_cast
。
reinterpret_cast
允許的轉換之一是將一個 object 指針類型轉換為另一個 object 指針類型。 其效果取決於確切的類型。 這在轉換為char*
或unsigned char*
以獲得 object 的 object 表示時非常有用。
reinterpret_cast<void*>
是沒有意義的,因為從任何(非const
/ volatile
)object 指針類型到void*
的轉換是隱式的。 演員根本不需要。 即使需要static_cast
也會做同樣的事情並且風險較小(因為大多數reinterpret_cast
的使用很可能以未定義的行為結束)。 此轉換不會更改指針值。 void*
將指向與原始指針相同的 object。 然后您需要稍后使用static_cast
將void*
轉換回原始類型(也不需要reinterpret_cast
)。 轉換為其他類型幾乎總是以未定義的行為結束。
reinterpret_cast
可以執行的另一種轉換是 object 類型指針和整數之間的轉換。 這會將 map 指針的地址以某種實現定義的方式指向 integer 值(並返回)。 同樣,唯一有用的方法是將從指針獲得的 integer 值轉換回其原始類型。 將隨機 integer 值強制轉換為指針也不太可能產生可用的指針值。 所有這些都是實現定義的(除了往返指針 -> 整數 -> 指針強制轉換保持值不變)。
然而,在允許將 class 類型轉換為指針類型的reinterpret_cast
的可能轉換列表中根本沒有特定的轉換。 所以CString
不能以這種方式轉換為void*
。 但是無論如何都沒有任何有意義的方法來進行這種轉換。 您希望得到的指針值代表什么?
你不應該在這里需要任何reintepret_cast
。 一個包含正確類型類型的簡單結構可以:
struct Params {
CInspectionDone* a;
int b;
};
void *pParam = new Parames{this, iTrayNumber};
_beginthreadex(NULL, 0, &CInspectionDone::InspectionDoneThread, pParam, 0, NULL);
然后InspectionDoneThread
可以使用static_cast<Params>(arg)->a
訪問參數並使用delete static_cast<Params>(arg);
.
或者甚至更好地使用現代 C++。從十年前開始就有std::thread
,它根本不需要任何指針。 InspectionDoneThread
可以只是一個非靜態成員 function 與 integer 作為具有適當類型的參數,而不需要是一個static
成員 function 與void*
參數。 接着:
auto mythread = std::thread(&CInspectionDone::InspectionDoneThread, this, iTrayNumber);
或者撥打 lambda:
auto mythread = std::thread([&]{ InspectionDoneThread(iTrayNumber); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.