Search code examples
c++classheap-memoryinstantiation

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


I need to use this class in a threaded application so instantiating it on the stack will obviously be a problem, is there a way to force new to be used when instantiating the class?

I have made the constructors private and the new operator public, something like

public:
    void *operator new(size_t);

private:
    SomeClass(void);
    SomeClass(SomeType value); 
               .
               .
               .

but as I expected when using

SomeClass *heapInstance = new SomeClass(value);

the compiler tells me that the constructor is private.

Question:

  • Is there a solution to this?

Note: I have used this class all over the place, and now I need to fix my code, i.e. I need the compiler to prevent compilation so I don't need to manually search for each occurrence, I am not very good at c++ I just had to use it because I needed to do a GUI cross platform application and picked Qt for several reasons which are irrelevant here.


Solution

  • 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.