Search code examples
c++void

assigning void pointer to another void pointer


Is it safe to assign void pointer to another void pointer such that both pointers will point to same thing, and then operate on one of them.

for example I'm trying to do something like this: (just an example) HANDLE is typedefed as void*

HANDLE hPrevious = INVALID_HANDLE_VALUE;

HANDLE hFile = CreateFile(...);

hPrevious = hFile; // assigning

CloseHandle(hPrevious); // now both handles are invalid?

hPrevious = INVALID_HANDLE_VALUE; // now both handles are INVALID_HANDLE_VALUE

// hFile is released

Is assigning one void* to another and then operating on one of them same as operating on both?


Solution

  • CloseHandle(hPrevious); // now both handles are invalid?
    

    Yep, they're both closed now.

    hPrevious = INVALID_HANDLE_VALUE; // now both handles are INVALID_HANDLE_VALUE
    

    This only modifies hPrevious. hFile is not changed. Pointers don't have any spooky action-at-a-distance until they're dereferenced with *.