如何检查指针是否指向正确对齐的内存位置? [英] How to check if a pointer points to a properly aligned memory location?

查看:287
本文介绍了如何检查指针是否指向正确对齐的内存位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给一个void *某个存储,如何检查它是否指向正确对齐的存储,而没有任何实现定义的行为?

Given a void * to some storage, how to check whether it points to properly aligned storage without any implementation defined behavior?

我们当然有 std::align ,但是有没有更有效的方法做到这一点的方法?

Of course we have std::align, but is there a more effective way to do this?

template <std::size_t alignment>
inline bool is_aligned(void * ptr) noexcept {
    std::size_t max = 1u;
    return std::align(alignment, 1u, ptr, max);
}

PS:我需要以C ++标准兼容的方式进行此操作,而不必依赖于任何特定于平台的(定义为实现)的黑客行为.

PS: I need to do this in a C++ standards-compatible fashion, without relying on any platform-specific (implementation defined) hacks.

PPS:我对我的(理解)英语(不是我的母语)表示歉意.

PPS: I apologize for my (comprehension of) English, its not my native language.

编辑(2018.08.24)::从标题中删除了有效",添加了更多措辞以强调我不希望定义任何实现或特定于平台的行为.

EDIT (2018.08.24): Removed "effective" from the title, added even more wording to emphasize that I don't want any implementation defined or platform-specific behavior.

推荐答案

如果用所需的对齐方式对地址进行除法运算时余数不为零,则该地址不对齐.

If the remainder isn't zero when dividing the address with the desired alignment, then the address isn't aligned.

inline bool
is_aligned(const void * ptr, std::uintptr_t alignment) noexcept {
    auto iptr = reinterpret_cast<std::uintptr_t>(ptr);
    return !(iptr % alignment);
}

由于类型转换,这些不能成为constexpr.

Ths can't be constexpr though, because of the cast.

此外,这还依赖于实现定义的事实,即从指针到整数的转换必须保留地址的数字表示形式.正如评论所指出的那样,这不是标准所保证的,因此此功能不一定可移植到所有平台.这也是正确的,因为实现提供std::uintptr_t是可选的.

Also, this relies on the implementation-defined fact that the conversion from pointer to integer must preserve the numeric representation of the address. As pointed out by the comments, that is not guaranteed by the standard, so this function is not necessarily portable to all platforms. That is also true, because it is optional for the implementation to provide std::uintptr_t.

我希望仅在对齐类型时才需要这样做,因此这可能更方便:

I would expect this to only be needed when aligning for a type, so this might be more convenient:

template<class T>
bool
is_aligned(const void * ptr) noexcept {
    auto iptr = reinterpret_cast<std::uintptr_t>(ptr);
    return !(iptr % alignof(T));
}

这篇关于如何检查指针是否指向正确对齐的内存位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆