Barnsley fern fractal

Thoughts on software architecture and development, and methods and techniques for improving the quality thereof.

David B. Robins (home)

Code Visions: Improving software quality
The compiler optimized out my destructor (and it was right)

By David B. Robins tags: C++, Bugs Tuesday, February 10, 2015 12:02 EST (link)

I do most of my testing with a debug build, which has fewer optimizations than release to make debugging easier (not "none", because that makes the binary image too big for the embedded device; -Og, actually). I was doing some pre-release testing with a release build, and noticed that the destructor for one of my objects didn't appear to be called in release builds (using -Os). This object was somewhat of a special case, since it was created with placement new and destroyed with an explicit destructor call; and I always had a faint feeling of not-quite-rightness with it, and now I know why.

The destructor set a state in the object to mark it as free, since it was one of several slots that could be activated when associated with a Bluetooth advertisement or connection. This is where you should be having uneasy feelings, because looking at destroyed objects is not kosher at all; in fact, it is undefined behavior (C++ standard N3690, 3.8 Object lifetime [], paragraph 5). Thus, the compiler reasons that if you are not allowed to look at the object's fields, then there's no point in wasting good CPU time setting them! So, the state was never set to free, and (in this particular case) the advertisement never expired; although this defect was hidden by another issue for a long time.

Fixed by using an explicit Free function.

Content on this site is licensed under a Creative Commons Attribution 3.0 License and is copyrighted by the authors.