limit the creation of object on heap and stack in C++
c++
Solution
To prevent accidental creation of an object on the heap, give it private operators new. For example:
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, and provide friend or static functions that perform the same functionality. For example, here's one that 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();
};
Problem
I have a question about how to limit the creation of object on heap or stack? For example, how to make sure an object not living on heap? how to make sure an object not living on stack? Thanks!