sizeof和alignof有什么区别? [英] What's the difference between sizeof and alignof?

查看:994
本文介绍了sizeof和alignof有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sizeof和alignof之间有什么区别?

What's the difference between sizeof and alignof?

#include <iostream>

#define SIZEOF_ALIGNOF(T) std::cout<< sizeof(T) << '/' << alignof(T) << std::endl

int main(int, char**)
{
        SIZEOF_ALIGNOF(unsigned char);
        SIZEOF_ALIGNOF(char);
        SIZEOF_ALIGNOF(unsigned short int);
        SIZEOF_ALIGNOF(short int);
        SIZEOF_ALIGNOF(unsigned int);
        SIZEOF_ALIGNOF(int);
        SIZEOF_ALIGNOF(float);
        SIZEOF_ALIGNOF(unsigned long int);
        SIZEOF_ALIGNOF(long int);
        SIZEOF_ALIGNOF(unsigned long long int);
        SIZEOF_ALIGNOF(long long int);
        SIZEOF_ALIGNOF(double);
}

将输出

1/1
1/1
2/2
2/2
4/4
4/4
4/4
4/4
4/4
8/8
8/8
8/8

1/1 1/1 2/2 2/2 4/4 4/4 4/4 4/4 4/4 8/8 8/8 8/8

我想我'

推荐答案

好吧,内存基本上是一个巨大的字节数组。然而,大多数的东西,例如整数,需要超过1个字节来存储它们 - 例如,一个32位的值将使用4个连续的内存字节。

Well, "memory" is basically a huge array of bytes. However, most larger things like integers need more than 1 byte to store them -- a 32 bit value, for example, would use 4 consecutive bytes of memory.

计算机中的内存模块通常不是字节;

Now, the memory modules in your computer aren't usually "bytes"; they are also organized with a few bytes "in parallel", like blocks of 4 bytes.

对于一个CPU来说,这更容易=更高效=更好的性能,而不是交叉这样的块边界时读取一个整数:

For a CPU, it's much easier = more efficient = better performance to not "cross" such block-borders when reading something like an integer:

memory byte    0 1 2 3     4 5 6 7       8 9 10 11
 integer       goooood
                   baaaaaaaaad

这就是alignment对齐方式为4意味着这种类型的数据应该(或者必须,取决于CPU)从一个4的倍数的地址开始存储。

This is what the "alignment" says: an alignment of 4 means that data of this type should (or must, depends on the CPU) be stored starting at an address that is a multiple of 4.

that sizeof == alignof是不正确的;尝试结构。结构也将对齐(因为它们的个体成员需要在正确的地址上结束),但是它们的大小将更大。

You observation that sizeof==alignof is incorrect; try structures. Structures will also be aligned (because their individual members need to end up on the correct addresses), but their size will be much larger.

这篇关于sizeof和alignof有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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