Search code examples
c++heap-memorynew-operator

Explicitly disallow heap allocation in C++


I have a number of classes that I would like to explicitly disallow heap allocation for. It occurred to me this weekend that I could just declare operator new private (and unimplemented)... Sure enough, this results in compile errors when you attempt to new the class... My question is: Is there more to this? Am I missing something or is this a good way of doing what I want?

#include <stdio.h>

class NotOnTheHeap
{
public:
  NotOnTheHeap() : foo( 0 )
  {
  }

private:
  void *operator new( size_t );
  void operator delete( void* );
  void *operator new[]( size_t );
  void operator delete[]( void* );

  int foo;
};

class Heapable
{
private:
  NotOnTheHeap noth;
};

int main( int argc, char* argv[] )
{
  NotOnTheHeap noth;

  Heapable* heapable = new Heapable;

  return 0;
}

Solution

  • Depends on what you mean with "explicitly disallow heap allocation".

    If you just want to prevent direct allocation on the heap, i.e.:

    NotOnTheHeap *n = new NotOnTheHeap();
    

    it is good enough. But it will not prevent that your object exists on the heap in general.

    For example, it won't prevent people from using std::vector <NotOnTheHeap>, which will allocate objects from your class on the heap.

    It will also not prevent people from using a NotOnTheHeap as member variable in another class, that is allocated on the heap.