c++ - 如何在 C++ 中正确转换结构

标签 c++ casting

考虑下面的代码摘录:

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);

如何使用 C++ 样式转换正确转换为 ULONG_PTR*?

附注它是依赖于平台的代码。

最佳答案

我想应该是 const_cast<ULONG_PTR*>(reinterpret_cast<const ULONG_PTR*>(&info)) .

来自 Effective C++,第 3 期。编辑,第 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 (i.e., unportable) results, e.g., casting a pointer to an int. Such casts should be rare outside low-level code.

为了完整起见,剩下的两个 C++ 转换是:

  • dynamic_cast is primarily used to perform "safe downcasting," i.e., 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 (e.g., 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 (e.g., 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.)

关于c++ - 如何在 C++ 中正确转换结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2938414/

相关文章:

c++ - 迭代器上的 vector 下标超出范围

c++ - libssh - 多次发送请求并从 channel 读取答案

dictionary - 将 map[string]string 转换为 map[someStruct]string

c - 了解类型转换

c - 是否通过强制转换为已签名的未定义行为来检测未签名的环绕?

c++ - 一个 QWebEnginePage 用于两个或多个 QWebEngineView

c++ - 在 C++ 的析构函数中调用 delete[]

c++ - 更改类内的结构或类 |有或没有指针

c - 什么 *(DWORD_PTR*)&functionA = functionB( var1, var2);做?

casting - 了解类型推断