Is it possible to force c++ class instantiation on the heap?

Just make ctor private/protected and provide a static method(s) to create an instance:

class HeapOnly {
     HeapOnly();
     HeapOnly( int i );
public:
     static HeapOnly *create() { return new HeapOnly; }
     static HeapOnly *create( int i ) { return new HeapOnly( i ); }
};

You may consider to return a std::unique_ptr in general case, but for Qt that could be not necessary.

This will not solve your problem instantly, but you will get compile error everywhere where instance is created and you can replace them by create function call catching places where class instance created on a stack.

Leave a Comment