简体   繁体   中英

How to cast correctly a struct in C++

Consider a code excerpt below:

typedef struct tagTHREADNAME_INFO {
    DWORD dwType;
    LPCTSTR szName;
    DWORD dwThreadID;
    DWORD dwFlags;
} THREADNAME_INFO;

const THREADNAME_INFO info = { 0x1000, threadName, CurrentId(), 0};

::RaiseException(kVCThreadNameException, 0,
    sizeof(info) / sizeof(ULONG_PTR),
    (ULONG_PTR*)&info);

How to cast correctly into ULONG_PTR* using C++ style cast?

ps it's platform dependent code.

I guess it would be const_cast<ULONG_PTR*>(reinterpret_cast<const ULONG_PTR*>(&info)) .

From Effective C++, 3rd. Ed., Item 27:

  • const_cast is typically used to cast away the constness of objects. It is the only C++-style cast that can do this.
  • reinterpret_cast is intended for low-level casts that yield implementation-dependent (ie, unportable) results, eg, casting a pointer to an int. Such casts should be rare outside low-level code.

And for the sake of completeness, the remaining two C++ casts are:

  • dynamic_cast is primarily used to perform "safe downcasting," ie, to determine whether an object is of a particular type in an inheritance hierarchy. It is the only cast that cannot be performed using the old-style syntax. It is also the only cast that may have a significant runtime cost.
  • static_cast can be used to force implicit conversions (eg, non- const object to const object (as in Item 3), int to double , etc.). It can also be used to perform the reverse of many such conversions (eg, void* pointers to typed pointers, pointer-to-base to pointer-to-derived), though it cannot cast from const to non- const objects. (Only const_cast can do that.)

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