Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 806
dicroce Avatar asked Dec 21 '09 17:12

dicroce


3 Answers

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.

like image 91
oefe Avatar answered Oct 20 '22 20:10

oefe


That will mostly achieve what you're trying.

What your solution does not cover is in-place new, which may or may not be on the heap.

like image 1
Drew Dormann Avatar answered Oct 20 '22 21:10

Drew Dormann


You could disable the copy or even default construction, and operator= etc for a more strict scenario (some cases of embedding values or container use).

However, that will move you out of some useful constructs and force you to introduce your own semantics (something more visible in VM impls; lack/induction of similar operator and ambiguous equivalence/equality mechanisms). You will likely see a few compiler warnings too, it won't go all the way, but if its of any consolation it can have a use or two.

like image 1
rama-jka toti Avatar answered Oct 20 '22 19:10

rama-jka toti