JavaKazRace - Playable Java racing game demo
PSEmu Pro GPU plug-in
DOSX Utils
SHLight 2004
JavaKazRace DSharingu PSEmuGPU DOSX Utils SHLight 2004

overloading

Pains of memory management and C++

Davide's picture

Recently, I felt the pain of hands-on C++ development again.

Because I use SSE2 instructions and because those need to work on at least 16-bytes aligned memory, using standard "new" and "delete" was out of the question.
I proceeded in overriding them globally and wxWidgets started working funny: it sometimes would use my globally defined "new" and "delete", sometimes it would use the standard Microsoft CRT.
I finally found out that I should have enabled global memory allocation using a specific option in wxWidget's "setup.h" file (a configuration file for compilation).

Next, I decided that I needed memory leak detection. But, because I'm overloading the allocation operator I can't use the MS CRT's leak detection.
For the memory manager to keep track of allocations I decided to use a fixed length STL-like vector. This vector (which basically contains an array) is built as a template class that accepts as parameters the type and the maximum size.

The vector was declared as static and this gave me another big problem that took me a while to track down. At startup my poor vector was actually being used as some other static functions from wxWidgets called "new" and "delete" before the vector was actually initialized.

Basically the issue being lack of dependency between statically allocated items (a well known issue in C++).
One way to fix that was to put the array into a function. Every time a "new" was called, it would call a function which would initialize the static array the first time.
This is called "construct on first use". It worked well to command initialization.. but would leave me in the dark on where the destructor would be called.

I eventually built a separate vector class without constructor and destructor 8)

I've also cleaned up a bit things with smart pointers... but it's really a mess with C++. On the other hand, the approach of languages designed form ground-up with automatic garbage collection doesn't seems like a great thing for performance when seeing how those things work when implemented in C++.. lots of work behind the scenes !
But then, maybe one shouldn't use pointers when performance is of essence.. easier said than done !

Syndicate content