c++stackheap-memory

How to prevent an object being created on the heap?


Does anyone know how I can, in platform-independent C++ code prevent an object from being created on the heap? That is, for a class "Foo", I want to prevent users from doing this:

Foo *ptr = new Foo;

and only allow them to do this:

Foo myfooObject;

Does anyone have any ideas?

Cheers,


Solution

  • Nick's answer is a good starting point, but incomplete, as you actually need to overload:

        private:
            void* operator new(size_t);          // standard new
            void* operator new(size_t, void*);   // placement new
            void* operator new[](size_t);        // array new
            void* operator new[](size_t, void*); // placement array new
    

    Or, for better compiler output in C++11 and beyond:

        private:
            void* operator new(size_t) = delete;   // delete standard new
            void* operator new[](size_t) = delete; // delete array new
    
            // explicitly deleting placement new, per the prior example,
            // does not seem to be necessary in modern compilers, but you
            // can if you find you need to
            void* operator new(size_t, void*) = delete;
            void* operator new[](size_t, void*) = delete; 
    

    (Good coding practice would suggest you "should" also overload the delete and delete[] operators -- I would, but since they're not going to get called it isn't really necessary.)

    Pauldoo is also correct that this doesn't survive aggregating on Foo, although it does survive inheriting from Foo. You could do some template meta-programming magic to HELP prevent this, but it would not be immune to "evil users" and thus is probably not worth the complication. Documentation of how it should be used, and code review to ensure it is used properly, are the only ~100% way.