2013-10-19 35 views
0

爲什麼下面的代碼中的賦值無法編譯?爲什麼這個易失性指針convserion無效

struct foo 
{ 
    int* m_NormalIntPointer; 
    int* volatile m_IntPointerModifiedByManyThreads; 


    void func() 
    { 
    //compiles fine 
    void* pointerToNormalPointer = &m_NormalIntPointer; 

    //does not compile 
    void* volatile* pointerToPointerModifiedByManyThreads = &m_IntPointerModifiedByManyThreads; 
    } 
}; 

如果m_IntPointerModifiedByManyThreads是一個指向一個int,並且該指針可以通過其它線程進行修改,並且「空隙*揮發性*」是一個指針,它指向可以通過其它線程被修改的指針,爲什麼用任務需要演員,其中非易失版本不?

+1

揮發性預選賽無關,跟線程,除非你使用Visual Studio – Cubbi

+0

@Cubbi的非標準擴展:或者使用IA64。 –

回答

1

這條線:

void* volatile* pointerToPointerModifiedByManyThreads = &m_IntPointerModifiedByManyThreads 

這是一個指向(void *)。讓我們忽略它是不穩定的,因爲它是不相關的。 (讓我們也忽略你使用volatile的事實時,你應該使用原子能公司:volatile幾乎從未有用的多線程編程。)

您可以將指針不能轉換爲(void *)的指針(int *)或反之亦然。就像您不能在指向struct x的指針和指向struct y的指針之間進行轉換,並且不能在指向(int *)的指針和指向struct x的指針之間進行轉換。這些轉換都不允許。

struct x my_x; 
struct y *my_yptr = &my_x; // not allowed 

int *my_intptr; 
void **my_voidptr = &my_intptr; // not allowed, for exact same reason 

唯一允許的轉換是指向void等的指針。

int my_int; 
void *my_voidptr = &my_int; // allowed 
int *my_intptr = my_voidptr; // allowed 

所以,如果你想要做的轉換,你必須轉換爲void *,不void **。由於int **是一個指針,您可以將其轉換爲void *並返回。

下面的代碼是正確的,但醜:

int x = 3, y = 4; 
int *my_intptr = &x; 
void *my_intptr_ptr = &my_intptr; 
*(int **) my_intptr_ptr = &y; 
**(int **) my_intptr_ptr = 7; 
// now y = 7, and my_intptr = &y