c++ - 一个空的class在内存中的大小问题
高洛峰
高洛峰 2017-04-17 13:54:32
0
8
407

比如有一个类定义如下:

class A{
};

当我们构造一个A类型的对象a,用sizeof(a)得出来的结果是1,在深入理解C++对象模型一书中,有如下的解释:
它有一个隐晦的1byte,那是被编译器安插进去的一个char,这使得这个class的两个objects得以在内存中配置独一无二的地址...

问题来了,为什么安插一个1byte的char就能配置出独一无二的地址?是怎么做到的?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(8)
巴扎黑

If not even one byte is allocated in the memory, then naturally there is no memory address that can represent this object, but even if only one byte is allocated, this object can be guaranteed to be allocated to a unique address.

刘奇

Please refer to this link: http://stackoverflow.com/questions/2362097/why-is-the-size-of-an-empty-class-in-c-not-zero

C++The standard does not allow a class that occupies 0 memory, because if there is such a class, two different class objects may occupy the same memory address.

Peter_Zhu

The standard in C++ stipulates that the smallest object, including native types char/int, etc., has a minimum value of 1. It is mainly used to distinguish different objects. Just imagine what you would do if the new thing does not occupy memory? Furthermore, if the address of your empty class is 0, then it stands to reason that the size of the array of the empty class is also 0? This is obviously a paradox

伊谢尔伦

This is because the minimum addressing unit of memory is 1 byte.
In other words, 8bit is a whole, which is the smallest unit for memory operations. 8bit is a byte.
Because the smallest unit of an integer is 1, and the memory address is an integer, each byte in the memory has a unique integer to represent its memory address. That is, the address of each byte is unique.
Note: The above remarks are just simple explanations of the problem and are not rigorous. There is no explanation of multi-processing, virtual addresses, etc.

迷茫
问题来了,为什么安插一个1byte的char就能配置出独一无二的地址?是怎么做到的?

The question needs to be re-explained. There is no magic here, classes are templates that generate objects, and objects must have a size to be allocated in memory, so giving 1 byte or multiple bytes has the same effect.

Ty80

In order to distinguish the addresses of two different objects

迷茫

It just allocates memory. 1 byte is the minimum allocation unit. You can allocate 2, 3, or 4 bytes, but it is a waste of memory.
So the program compiled by the compiler will only allocate the minimum memory. , which is 1 byte

As for 独一无二, the memory address is of course unique. If the two memory addresses are the same,
then how to read and write them? Memory operations are all performed through addresses
The address is their ID (the only certain ID card), so it’s good to understand it

伊谢尔伦

You allocate 1 byte of memory, this is the only memory of the machine

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!