uintptr_t 便携式替代方案
我想检查某种类型 T
的内存对齐情况。 然而,执行此操作的直接方法是
if (((uintptr_t)&var & __alignof(T) - 1) == 0) ...
,uintptr_t
不是现有 C++ 标准的一部分,并且某些编译器不支持它,因此我正在寻找一种可移植的替代方法来执行此操作,并且std::ptrdiff_t
看起来对我来说不错。 std::ptrdiff_t
保证能够存储两个指针之间的差异,但谁说其中一个指针不能为空指针?在这种情况下,std::ptrdiff_t 的大小必须至少与指针本身相同。
template <typename T> bool is_properly_aligned(const T* const ptr)
{
std::ptrdiff_t diff = (ptr - static_cast<T*>(0)) * sizeof(T);
return ((diff & __alignof(T) - 1) == 0);
}
或者像这样(摆脱乘法 sizeof(T)
)
template <typename T> bool is_properly_aligned(const T* const ptr)
{
std::ptrdiff_t diff =
reinterpret_cast<const char*>(ptr) - static_cast<const char*>(0);
return ((diff & __alignof(T) - 1) == 0);
}
您对这种解决方案有何看法?它足够便携吗?我没有看到任何失败的原因,但我想确认一下。
谢谢。
I want to perform check for memory alignment of some type T
. The straightforward way to do this is
if (((uintptr_t)&var & __alignof(T) - 1) == 0) ...
however, uintptr_t
is not part of existing C++ standard and it is not supported by some compilers, so I'm looking for a portable alternative way to do this and std::ptrdiff_t
looks good for me. std::ptrdiff_t
guaranteed to be able to store difference between two pointers, but who says that one of those pointers cannot be null pointer? In that case std::ptrdiff_t
has to be at least same size as the pointer itself.
template <typename T> bool is_properly_aligned(const T* const ptr)
{
std::ptrdiff_t diff = (ptr - static_cast<T*>(0)) * sizeof(T);
return ((diff & __alignof(T) - 1) == 0);
}
or like that (to get rid of multiplication by sizeof(T)
)
template <typename T> bool is_properly_aligned(const T* const ptr)
{
std::ptrdiff_t diff =
reinterpret_cast<const char*>(ptr) - static_cast<const char*>(0);
return ((diff & __alignof(T) - 1) == 0);
}
What do you think about such kind of solution? Is it portable enough? I don't see any reasons why this should fail, however I would like to confirm.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定这里的问题是什么。 “你怎么认为?”我认为 ptrdiff_t 确实是表示两个指针之间差异的正确数据类型,但是如果两个指针没有指向来自简单分配的连续内存块(并且作为推论,两者都没有),那么比较两个指针就没有什么意义。被比较的两个指针的值应该为 NULL)。
I'm not sure what the question here is. "What do you think?" I think ptrdiff_t is indeed the correct datatype to represent the difference between two pointers, but it makes very little sense to compare two pointers if they are not pointing into a block of contiguous memory that comes from a simple allocation (and as a corollary, neither of the two pointers being compared should ever be NULL).