如何检查类型正确的类型指针? [英] How do I check a typed pointer is properly aligned for that type?

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

问题描述

假设我有一个模板化函数,处理指向未知类型 T 的指针。现在,如果在64位平台上类型 T 恰好是 void * ,则它必须是8字节对齐的,但是如果 T 恰好是 char ,则必须对齐1个字节,并且 T 恰好是一个类,因此其对齐要求将取决于其成员变量。

Suppose I have a templated function that deals with pointers to yet unknown type T. Now if type T happens to be void* on 64-bit platform then it must be 8-bytes aligned, but if T happens to be char it must be 1-byte aligned and if T happens to be a class then its alignment requirements will depend on its member variables.

所有这些都可以在纸上进行计算,但是我如何使编译器产生给定类型 T 的对齐要求吗?

This all can be computed on paper, but how do I make the compiler yield the alignment requirements for a given type T?

有没有办法在编译时找到对齐方式

Is there a way to find during compile time the alignment requirements for a given type?

推荐答案

在C ++ 11中,您可以使用 alignof alignas 进行断言并提供对齐要求。另请参阅 std :: align 以控制运行时的对齐方式。

In C++11 you can use alignof and alignas to make asserts and provide requirements for alignment. Also look at std::align to control alignment in runtime.

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

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