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)... 开发者_如何学JAVASure 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;
}
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.
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.
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.
Can't you just make the implementation of operator new an assert(0)?
精彩评论