Let's say you have a struct with two integers that are initialized to 1 and 2 in the struct constructor:
struct two_ints
{
int a;
int b;
two_ints() : a(1), b(2) {}
};
Let's also say you have a 45-byte heap memory space, like the graph shown below.
1 2 3 4
0 5 0 5 0 5 0 5 0 5
|||||||||||||||||||||||||||||||||||||
Now, if you instantiate a two_ints struct on the 45-byte heap like this:
two_ints* ints = new two_ints();
Then, graphically, what operator new will do for you in this example is this:
1 2 3 4
0 5 0 5 0 5 0 5 0 5
|||||||||||||||||||||||||||||||||||||
aaaabbbb
----
^ ----
| ^
| |
| +-- 4 bytes for field b
|
+-- 4 bytes for field a
|
+-- on address 20 in this 45-byte memory space
Or in words, it will:
- Allocate 8 bytes of memory for 2 4-byte integers, starting at memory address 20 (in this example).
- Run the constructor that assigns the values 1 and 2 to
a and b, meaning that the aaaa and bbbb memory slots in the diagram above is set to 0001 and 0002, or 1000 and 2000, depending on the platform endianess.
- Return the address 20.