Handmade Hero » Forums » Code » Question on comment made in HMH day 005 - Graphics Review concerning c++ constructors and destructors
boagz57
Jason
19 posts
#13937 Question on comment made in HMH day 005 - Graphics Review concerning c++ constructors and destructors
4 months, 2 weeks ago Edited by Jason on Jan. 7, 2018, 2:40 p.m. Reason: Initial post

Hi everyone,

Background:

At around 12:30 in day 005 - 'Graphics Review' Casey was asked why the Windows MSG struct was placed inside his 'while' loop instead of outside it. Casey explained that there really was no difference performance wise since the compiler can just move the struct outside the loop and avoid constant reallocation of the struct as the stack grows and shrinks. It was more to make sure things were lexically scoped. He then went on to say that in C++ this would be different because classes have constructors and destructors and compilers are 'mandated' by C++ to always construct and destruct upon entry and exit of a function or scope, but that he would almost never do this in his code.

My confusion:

But the code we are compiling is c++ code (hence the .cpp extension on win32_handmade file) and as far as I'm aware even structs in c++ have constructors and desctructors. So the windows MSG struct WOULD be constructed and destructed constantly if inside the while loop scope, correct? Or is there some misunderstanding/confusion on my part?
mmozeiko
Mārtiņš Možeiko
1670 posts
1 project
#13939 Question on comment made in HMH day 005 - Graphics Review concerning c++ constructors and destructors
4 months, 2 weeks ago Edited by Mārtiņš Možeiko on Jan. 7, 2018, 3:14 p.m.

C++ can see the struct declaration and reason about its behavior. It "sees" that it has no complex C++ members, that means it is POD-struct (plain-old-datatype). No fancy constructors or destructors are needed, so it simply allocates space on stack and does not call any code for its "construction" or "destruction". Another way how to look at it is that POD struct constructors and destructors are empty. So there is no code to generate, that's why compiler is free to move stack space allocation wherever it wants.
boagz57
Jason
19 posts
#13941 Question on comment made in HMH day 005 - Graphics Review concerning c++ constructors and destructors
4 months, 2 weeks ago

Fantastic! Thank you so much for that clarification. Completely forgot about POD types.
ratchetfreak
359 posts
#13942 Question on comment made in HMH day 005 - Graphics Review concerning c++ constructors and destructors
4 months, 2 weeks ago

Don't forget that allocation and construction are separate.

The compiler is free to reuse the stack space allocated for local variables in a loop for the next iteration and optimize out the addition and subtraction of the stack register.

In fact moving the allocation to the start of the function is the most basic optimization the compiler does.