C++ stack only object
To complete the discussion on object creation constraint by memory location. We shall see how one can force object creation on stack only. Again, the code is very simple:
class A{
private:
void * operator new(size_t size) {}
};
int main(){
A a;
A * b;
A * c = new A;
}
One needs to declare a private 'operator new' in stack only bound object. The trick is this: C++ distinguishes between 'new operator' (as used in A * c = new A) and 'operator new' (declared in class A). However, beneath the hood, 'new operator' calls 'operator new' to dynamically allocate an object. Once the 'operator new' is declared as private, the built-in 'new operator' can no longer access it and such a class cannot be instantiated on heap.
class A{
private:
void * operator new(size_t size) {}
};
int main(){
A a;
A * b;
A * c = new A;
}
One needs to declare a private 'operator new' in stack only bound object. The trick is this: C++ distinguishes between 'new operator' (as used in A * c = new A) and 'operator new' (declared in class A). However, beneath the hood, 'new operator' calls 'operator new' to dynamically allocate an object. Once the 'operator new' is declared as private, the built-in 'new operator' can no longer access it and such a class cannot be instantiated on heap.
<< Home