I\'ve got some code that uses type-punning to avoid having to call a member \"object\"\'s constructor and destructor unless/until it\'s actually necessary to use the object.
What if you replace _isObjectConstructed with a pointer to the object:
class Lightweight
{
public:
Lightweight() : object(NULL) {/* empty */}
~Lightweight()
{
// call object's destructor, only if we ever constructed it
if (object) object->~T();
}
void MethodThatGetsCalledOften()
{
// Imagine some useful code here
}
void MethodThatGetsCalledRarely()
{
if (!object)
{
// demand-construct the heavy object, since we actually need to use it now
object = new (_optionalObject._buf) T();
}
object->DoSomething();
}
private:
union {
char _buf[sizeof(T)];
unsigned long long _thisIsOnlyHereToForceEightByteAlignment;
} _optionalObject;
T *object;
};
Note, no GCC extension, only pure C++ code.
Using a T* instead of a bool won't even make Lightweight any bigger!