我的类包含 1 个枚举、2 个 int 和一个指针。它没有虚函数,但测量 20 字节。为什么?
My class contains 1 enum, 2 int's and a pointer. It has no virtual functions but measures 20 bytes. Why?
根据标题。我真的不想列出它包含的所有其他成员,但我惊讶地发现,给定唯一的非静态数据成员是int
的enum
、2和指向它自己类型的指针,它的sizeof
应该是20。
它没有虚拟函数,我已经将指针和enum
分别测量为4个字节。我应该更努力地寻找其他成员吗?
当从文件中读回时,我需要这些信息来为其类型的n个对象分配缓冲区。
平台:bada,环境:gcc和Eclipse在Win7 x64中。
enum blockParams {enum1, enum2, /**/};
class Block : public Object {
public:
int begin;
protected:
Block() : begin(-1), end(UNCLOSEDBLOCK) {}
//Last index
int end;
private:
blockParams1 params;
const Block *parentBlock;
//Lots and lots (~80) member functions and static data members.
}
编译器可以自由地在成员之间引入填充,以实现各种对齐要求。
许多编译器提供了一种不可移植的方式来更紧密地封装结构(例如GCC的__attribute ((packed))
),但很少有充分的理由使用这种方式。
当我看到一个名为Object
的基类型时,我真的怀疑没有虚拟函数的说法。
如果正确使用sizeof,则不需要知道结构的大小,编译器将为您正确计算缓冲区大小。
20的大小可能包括编译器为提高效率而添加的填充。
大小是部分+填充的总和。
int main()
{
std::cout << "Object: " << sizeof(Object) << "n";
std::cout << "int: " << sizeof(int) << "n";
std::cout << "blockParams1: " << sizeof(blockParams1) << "n";
std::cout << "Block*: " << sizeof(Block*) << "n";
int estimatedSize = sizeof(Object) + (2 * sizeof(int)) + sizeof(blockParams1) + sizeof(Block*);
int actualSize = sizeof(Block);
std::cout << "Block: " << actualSize << "n";
std::cout << "Padding + implementation defined data for virtual functions: " << (actualSize - estimatedSize) << "n";
}
在对象为空的情况下运行此操作:
> ./a.out
Object: 1 // Note: This may be optimized away in Block.
// All objects must have non 0 size but when they are a base class
// you can optimize an actual zero sized object away.
int: 4
blockParams: 4
Block*: 8
Block: 24
Padding + implementation defined data for virtual functions: 3
// Note because the Object size 1 will be optimized away this is actually 4.
使用包含虚拟析构函数的对象运行此
> ./a.out
Object: 8
int: 4
blockParams: 4
Block*: 8
Block: 32
Padding + implementation defined data for virtual functions: 4
// Note It will use the area in Object for virtual functions so it does not
// Explicitly need any itself (in this implementation using a vtable).
如果我们假设您的平台上的指针是4个字节(并且您有带有虚拟函数的Object)。我希望看到:
> ./a.out
Object: 4
int: 4
blockParams: 4
Block*: 4
Block: 20
Padding + implementation defined data for virtual functions: 0
相关文章:
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- 用于测量重载运算符和成员函数的时间的函数
- C++ 测量重复调用的函数的时间
- 尝试构造包装器测量函数调用时间时出现问题
- 模式匹配函数的时间测量无法正常工作
- 测量将参数传递到函数所需的时间
- 测量其他类中函数的时间
- 测量函数调用期间的最大内存使用量
- 使用Clock()函数测量程序的运行时间
- 测量C 中函数调用的执行时间
- 测量cpp中的函数内存使用情况
- 如何测量Arduino函数的执行速度?
- 我的类包含 1 个枚举、2 个 int 和一个指针。它没有虚函数,但测量 20 字节。为什么?
- C++测量函数调用和回调之间的时间
- 如何测量c++中特定函数的运行时间{非常准确}
- 是否有一种方法可以测量特定函数从堆栈中消耗了多少内存?
- 在c++中做实验时,测量某些函数的cpu时间的最佳方法是什么?
- 我如何测量我的函数的时间,只有我的函数在使用CPU
- 如何在freeRTOS中使用vApplicationTickHook()函数来测量任务执行时间
- c++ STL:为什么STL数据结构不提供测量内存消耗的函数?