【问题标题】:Why did the author use reinterpret_cast?作者为什么使用reinterpret_cast?
【发布时间】:2018-05-31 01:35:46
【问题描述】:

这里是Effective C++ Item 50的代码sn-p:

static const int signature = 0xDEADBEEF;

typedef unsigned char Byte;

// this code has several flaws — see below
void* operator new(std::size_t size) throw(std::bad_alloc)
{
    using namespace std;
    size_t realSize = size + 2 * sizeof(int); // increase size of request so 2
    // signatures will also fit inside
    void *pMem = malloc(realSize); // call malloc to get the actual
    if (!pMem) throw bad_alloc(); // memory

    // write signature into first and last parts of the memory
    *(static_cast<int*>(pMem)) = signature; 
    *(reinterpret_cast<int*>(static_cast<Byte*>(pMem)+realSize-sizeof(int))) = signature;
    // return a pointer to the memory just past the first signature
    return static_cast<Byte*>(pMem) + sizeof(int);

}

为什么作者使用reinterpret_cast而不是static_cast?我可以只用reinterpret_caststatic_cast 替换所有四个演员吗?

【问题讨论】:

  • 你注意到说代码错误的评论了吗?你读过下面的解释吗?这些取消引用的指针转换需要替换为memcpy

标签: c++ casting type-conversion


【解决方案1】:

为什么作者使用reinterpret_cast而不是static_cast

static_cast 可以将指针类型转换为void* 并将其转换回来,但它不能在指向不相关类型的指针之间进行转换。 reinterpret_cast 可以。

5) 任何指向 T1 类型对象的指针都可以转换为指向 另一种类型 cv T2 的对象。这完全等同于 static_cast&lt;cv T2*&gt;(static_cast&lt;cv void*&gt;(expression))(这意味着 如果 T2 的对齐要求不比 T1 严格,则 指针的值不改变并转换结果 返回其原始类型的指针产生原始值)。在任何 在这种情况下,只有在允许的情况下才能安全地取消引用结果指针 通过类型别名规则(见下文)

【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 2018-12-11
    • 2020-05-11
    • 1970-01-01
    • 2015-05-15
    • 2018-04-30
    • 2013-09-22
    • 2013-01-19
    相关资源
    最近更新 更多