在我的平台上,long int 和 long long int 是相同的(64 位)。我有一个指向 long int 的指针,我想将它转换为指向 long long int 的指针。以下代码
static_cast<long long int*>(pointer);
是不允许的。在 C++11 中执行此操作的正确方法是什么?
最佳答案
你必须强制“重新解释”指针:
reinterpret_cast<long long int*>(pointer);
这样的转换意味着编译器“停止检查,我知道如何更好地解释该表达式中的二进制数据”。因此,无论何时制作 reinterpret_cast
- 检查您对平台、内存对齐等的了解。编写一些简单的单元测试等,通过 valgrind 或地址 sanitizer 运行它们。
所以现在想想,如果你真的需要转换这样的指针。通常重新设计功能等可以解决此类问题(例如,如果您只需要来自指向值的数据 - 将其存储在一些额外的变量中等)。
您也可以尝试强制编译器进行一些检查:
template <typename Dest, typename Src>
Dest* safe_pointer_cast(Src* src)
{
static_assert(sizeof(Src) == sizeof(Dest), "size of pointed values differ");
static_assert(alignof(Src) == alignof(Dest), "alignment different");
return reinterpret_cast<Dest*>(src);
}
关于c++ - 将 long int* 转换为 long long int*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32350681/