Sobes.tech
Junior — Middle

How does the new operator determine the amount of memory needed for allocation?

sobes.tech AI

Answer from AI

The new operator in C++ allocates memory for an object of a specified type and returns a pointer to it. The amount of memory to allocate is determined by the compiler at compile time, based on the size of the type.

For example, for new int, the compiler knows that int takes up, say, 4 bytes, and allocates exactly that much memory.

In the case of user-defined types (structures, classes), the size is calculated as the sum of the sizes of all fields, considering alignment.

Example:

int* p = new int; // allocates sizeof(int) bytes

struct S {
    int a;
    double b;
};

S* s = new S; // allocates sizeof(S) bytes, considering fields and alignment

Thus, new does not calculate the size dynamically at runtime but uses the size information of the type known at compile time.