After reading TobiMcNamobi's answer, I remembered placement new and got an idea how to solve my problem. The following test reliably fails unless I initialize active_
in the constructor:
#include <gmock/gmock.h>
#include <vector>
class MyClass {
public:
// Note: Constructor doesn't initialize active_
MyClass() {}
bool isActive() const { return active_; }
private:
bool active_;
};
TEST(MyClass, isNotActiveUponCreation) {
// Memory with well-known content
std::vector<char> preFilledMemory(sizeof(MyClass), 1);
// Create a MyClass object in that memory area using placement new
auto* myObject = new(preFilledMemory.data()) MyClass();
ASSERT_FALSE(myObject->isActive());
myObject->~MyClass();
}
Now I'll admit that this test is not the most readable one, and likely not immediately clear at first sight, but it works reliably and independent of any 3rd-party tools like valgrind. Is it worth the additional effort? I'm not sure. It heavily depends on MyClass
internals, which will make it very brittle. Anyway, it is one way to test for correctly initialized objects in C++..