Handmade Hero»Forums»Code
Jason
235 posts
Question on comment made in HMH day 005 - Graphics Review concerning c++ constructors and destructors
Edited by Jason on 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?
Mārtiņš Možeiko
2562 posts / 2 projects
Question on comment made in HMH day 005 - Graphics Review concerning c++ constructors and destructors
Edited by Mārtiņš Možeiko on
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.
Jason
235 posts
Question on comment made in HMH day 005 - Graphics Review concerning c++ constructors and destructors
Fantastic! Thank you so much for that clarification. Completely forgot about POD types.
511 posts
Question on comment made in HMH day 005 - Graphics Review concerning c++ constructors and destructors
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.