Meditation, The Art of Exploitation

Thinking? At last I have discovered it--thought; this alone is inseparable from me. I am, I exist--that is certain. But for how long? For as long as I am thinking. For it could be, that were I totally to cease from thinking, I should totally cease to exist....I am, then, in the strict sense only a thing that thinks.

Wednesday, April 25, 2007

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{
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.