Tag Archives: data structure

avoid object creation on heap/stack

To prevent accidental creation of an object on the heap:

assign private operators new. For example:
class X {
void *operator new(size_t);
void *operator new[](size_t);
To prevent accidental creation on the stack:

make all constructors private, and/or make the destructor private, and provide friend or static functions that perform the same functionality.

For example, here’s one where both constructor and destructor are declared private:
class X {
static X *New() {return new X;}
static X *New(int i) {return new X(i);}
void Delete(X *x) {delete x;}
X(int i);