C ++类/结构大小 [英] C++ Class/Structure size

查看:149
本文介绍了C ++类/结构大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类/ struct的大小有一些问题
这里是我的Graphnode.h,我只有4 vars - 一个16-unsigned char数组,三个unsigned char,我认为大小应该是19.为什么是32?

  Graphnode currentNode; 
cout<< sizeof(currentNode)<< endl; //为什么这是32?
cout<< sizeof(currentNode.state)<< endl; // this is 16

Graphnode.h:

  #include< stdio.h> 
#include< stdlib.h>
#include< tr1 / array>

// using namespace std;
class Graphnode {

public:
std :: tr1 :: array< unsigned char,16>州;
unsigned char x;
unsigned char depth;
unsigned char方向;
Graphnode(std :: tr1 :: array< unsigned char,16>,unsigned char,unsigned char,unsigned char);
Graphnode();

};
Graphnode :: Graphnode()
{
int i = 0;
for(i = 0; i <16; i ++)
{
state [i] = 0;
}
x = 0;
depth = 0;
direction = 0;
}

Graphnode :: Graphnode(std :: tr1 :: array< unsigned char,16> _state,unsigned char _x,unsigned char _d,unsigned char _direction)
{
int i = 0;
for(i = 0; i <16; i ++)
{
state [i] = _state [i]
}
x = _x;
depth = _d;
direction = _direction;
}


解决方案

输出数据结构成员一个接一个;它也会在两者之间留下填充



通常这意味着任何结构将是一定数量的倍数,取决于它包含的类型和目标平台,即使字段的大小的总和较小。



所有编译器通常提供 a>非标准扩展程序,可让您将此打包程序控制为较小或更高的程度。


Hi I have some problem about the size of a class/struct Here is my Graphnode.h, I only have 4 vars in it- one 16-unsigned char array, three unsigned char, I think the size should be 19. Why is it 32?

Graphnode currentNode; 
cout<< sizeof(currentNode)<<endl;// why this is 32 ?
cout<< sizeof(currentNode.state)<< endl;// this is 16

Graphnode.h:

#include <stdio.h>
#include <stdlib.h>
#include <tr1/array>

//using namespace std;
class Graphnode {

public:
    std::tr1::array<unsigned char, 16> state;
    unsigned char x;
    unsigned char depth;
    unsigned char direction;
    Graphnode(std::tr1::array<unsigned char, 16>,unsigned char,unsigned char, unsigned char);
    Graphnode();

};
Graphnode::Graphnode()
{
    int i=0;
    for(i=0;i<16;i++)
    {
       state[i] = 0;
    }
    x = 0;
    depth = 0;
    direction = 0;
}

Graphnode::Graphnode(std::tr1::array<unsigned char, 16> _state,unsigned char _x,unsigned char _d,unsigned char _direction)
{   
    int i=0;
    for(i=0;i<16;i++)
    {
       state[i] = _state[i];
    }
        x = _x;
        depth = _d;
        direction = _direction;
}

解决方案

Because the compiler does not lay out the data structure members one directly after the other; it also leaves padding in between.

Usually this means that any structure will be a multiple of some amount dependent on the types it contains and the target platform, even if the sum of the sizes of the fields is less.

All compilers typically offer non-standard extensions that let you control this packing to a lesser or greater degree.

这篇关于C ++类/结构大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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