2010-10-09 30 views
0

我想轉換爲int(或unsigned int)的指針,無論我嘗試它不想工作。的空調風格錯誤:從'美孚*'轉換爲'無符號詮釋'失去精度

我試過static_cast<intptr_t>(obj)reinterpret_cast<intptr_t>(obj),以及各種組合投射,intptr_t的,unsigned int的,而我包括stdint.h。從我讀過的內容來看,我嘗試過的很多事情中的一件應該是有效的。是什麼賦予了?

我沒有理會包括代碼,因爲它正是我所描述的,但既然你問,我已經嘗試了所有這些再加上其他的組合:

void myfunc(Foo* obj) 
{ 
    // ... 
    uintptr_t temp = reinterpret_cast<uintptr_t>(obj); 
    uintptr_t temp = static_cast<uintptr_t>(obj); 
    uintptr_t temp = (uintptr_t)obj; 
    intptr_t temp = reinterpret_cast<intptr_t>(obj); 
    intptr_t temp = static_cast<intptr_t>(obj); 
    intptr_t temp = (intptr_t)obj; 
    unsigned int temp = reinterpret_cast<unsigned int>(obj); 
    unsigned int temp = static_cast<unsigned int>(obj); 
    unsigned int temp = (unsigned int)obj; 
    // ... 
} 

他們都給出確切的同樣的錯誤。

+1

你在鑄造的?告訴我們問題不是這一步。 – GManNickG 2010-10-09 22:36:59

+0

你爲什麼這樣做?此外,請包括問題代碼。 – JoshD 2010-10-09 22:38:05

+0

你使用什麼編譯器? – 2010-10-09 22:44:52

回答

5

您可能在sizeof (Foo*) > sizeof (unsigned)的平臺上,或者您的編譯器設置爲警告有關不可移植的代碼。請注意,大多數64位編譯器,LP64和LLP64都屬於這一類。

沒有要求指針適合int。這是intptr_t的整點。

如果您使用的第三方庫在callbacls期間僅爲用戶上下文提供int,則可以將索引傳遞到查找表中,以便指針本身存儲在查找表中。這具有類型安全並且不會打破別名假設的額外好處。

編輯:適合我。 (Comeau "tryitout"是非常方便)

#include <stdint.h> 

void myfunc(class Foo* obj) 
{ 
    uintptr_t temp = reinterpret_cast<uintptr_t>(obj); 
} 

Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C++ C++0x_extensions

"ComeauTest.c", line 5: warning: variable "temp" was declared but never referenced uintptr_t temp = reinterpret_cast(obj);reinterpret_cast(obj);

In strict mode, with -tused, Compile succeeded (but remember, the Comeau online compiler does not link). Compiled with C++0x extensions enabled.

在C89模式它也適用:

#include <stdint.h> 

void myfunc(struct Foo* obj) 
{ 
    uintptr_t temp = (uintptr_t)obj; 
} 

Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C90

"ComeauTest.c", line 3: warning: declaration is not visible outside of function void myfunc(struct Foo* obj) ^

"ComeauTest.c", line 5: warning: variable "temp" was declared but never referenced uintptr_t temp = (uintptr_t)obj; ^

In strict mode, with -tused, Compile succeeded (but remember, the Comeau online compiler does not link).

+0

Right,and I've嘗試intptr_t,我仍然遇到錯誤。 'intptr_t test = reinterpret_cast (obj)'不起作用。 – Alex 2010-10-09 22:42:06

+0

使用'intptr_t'時出現同樣的錯誤嗎? – 2010-10-09 22:42:58

+0

原來我是一個白癡:P我在我的文件中有其他地方的第二個實例,我忘記了它(這個編譯在我的另一臺計算機上很好的btw)。即使得到正確的結果,我仍然看到錯誤消息,但他們現在指着另一個我做錯誤投射的實例,並且我沒有注意到行號的變化。謝謝你的幫助 – Alex 2010-10-09 23:05:38

相關問題