I'd always recommend using static_cast
instead of reinterpret_cast
in any situation where the static_cast
isn't rejected by the compiler. If possible try to avoid doing any casting at all - in this case you probably want: Y* y = &x.y
.
To answer the comment:
In this case, I have a PROCESS_MEMORY_COUNTERS_EX
variable. However the WinAPI function GetProcessMemoryInfo takes a
PROCESS_MEMORY_COUNTERS*. The former type starts with the exact same
fields as the latter, and adds a few at the end. The intended usage is
to pass into the function a pointer to the latter type, even if we
hold a pointer to the former (larger) type.
The documentation for GetProcessMemoryInfo() states that the second parameter is:
A pointer to the PROCESS_MEMORY_COUNTERS or PROCESS_MEMORY_COUNTERS_EX
structure that receives information about the memory usage of the
process.
The Win32 API is a C API, and not a C++ one, so you can just use a C style cast here, or preferably a reinterpret_cast
to make your intention clearer. I'd expect static_cast
to be rejected by the compiler in this case. Note that the third cb
parameter is there to tell the function which type of structure you actually provided - it should be set to either sizeof(PROCESS_MEMORY_COUNTERS)
or sizeof(PROCESS_MEMORY_COUNTERS_EX)
.