Why is my empty optional non-empty when I heap-allocate a single byte inside Microsoft's CppUnitTest framework?
09:51 11 Dec 2025

The following test asserts, which indicates that x has a value while it should be empty:

#include 

#include 
#include 
#include 

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

template
class B : public TestClass {
    void __Invoke(TestClassImpl::__voidFunc m) override {
        auto x = new bool(true);  // switch to false and it passes!
        TestClass::__Invoke(m);
        delete x;
    }
};

class C : public B {
    TEST_METHOD(M) {
        for (auto x : std::initializer_list>({std::nullopt})) {
            Assert::IsFalse(x.has_value());
            [[maybe_unused]] char c[23010];
            [[maybe_unused]] auto t = std::stacktrace::current();
        }
    }
};

I use class B to add inject some general functionality into Microsoft's CppUnitTest framework - in my case, a watch dog to monitor test execution time the sole purpose of which is to log something and kill the process in a case a test exceeds some timeout.

This works great. but with large stacks (compare the 23 kiB of chars in my TEST_METHOD), this leads to x being corrupted. Why?

More information:

  • This happens only in Release mode, not in Debug mode.

  • This happens only when heap-allocating (new bool, make_unique, ...) but not when stack-allocating in the same location.

c++ inheritance memory-corruption microsoft-cpp-unit-test