To prevent the object from being accidentally created on the heap, give it private operators new. For instance:
class X {
private:
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, as well as provide friendly or static functions that perform the same functions. For example, here, which does both:
class X {
public:
static X *New() {return new X;}
static X *New(int i) {return new X(i);}
void Delete(X *x) {delete x;}
private:
X();
X(int i);
~X();
};
please delete me
source
share