简体   繁体   中英

Simplify dereferencing void pointer

This WINAPI thread callback:

DWORD WINAPI dont_thread_on_me(LPVOID context) {
    int value = *((int *)context);
    return ERROR_SUCCESS;
}

in particular the line:

    int value = *((int *)context);

works. But *((int *)context) is all sorts of nasty. Is there a better way to write that?

int value = *reinterpret_cast<int *>(context);

如果需要的话,您真的无法绕开事实。

您可以使用reinterpret_cast

int value = *reinterpret_cast<int *>(context);

The compiler must know how to treat the context . So you have to tell the compiler with a cast that it points to an int . You can hide this with a macro like

#define read_as_int(p) *(reinterpret_cast<int*>(p))

int value = read_as_int(context);

but this doesn't improve neither readability nor effort to type the code. C++ purists might prefer an inline function:

int inline read_as_function(void*p) 
{ 
    return *(reinterpret_cast<int*>(p));
}

Although the question is tagged C++, it is perfectly valid as a C question as well (and I never can tell if people tag questions accurately), so ...

In C, it is often written:

foo( void *v ) {
  int *ip = v;
  int x = *ip;

Whether this is elegant or a gaping hole in the type system is a matter of personal preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM