Hello, I wonder what the memory allocated to the object depends on when it is created. Thank you in advance.
2 answers
On the size of the object, of course. In particular, on the sum of the sizes of its fields (if it is a structure or an instance of a class) or on the system capacity (if it is a scalar type). To accurately determine how much memory is allocated for a specific object, use the sizeof construct (object) . Just keep in mind that if one of the object fields is a pointer to which a dynamically created array is hung, then this method will give an inaccurate result: it will determine the size of the pointer (4 bytes in 32-bit systems, 8 bytes in 64-bit), and not the size allocated for an array of space.
- what is inaccurate here? - renegator
An object is allocated as much memory as it occupies. It depends on the number, location and size of its fields. The size of the object does not always coincide with the sum of the sizes of its fields.
For example, if a class uses virtual functions, then it will weigh down on the size of the pointer.
There is also such a thing as aligning members in structures. The compiler may insert a void between the fields so that the next field is aligned, that is, it has an address that is a multiple of 2, 4, 8, depending on the alignment chosen. Accessing unaligned data degrades performance, and on some architectures even leads to an error.
Also note that if an object uses dynamic memory, then the size of the object will not change. Take place only the pointer. Same with containers. No matter how many millions of elements there are, they will always be the same size.
Therefore, to find out the size of an object, it is better to use the sizeof operator, and not consider it yourself.