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++ heap only object


> Hi all,
> All I want to achieve is restricting the object instantiation in stack
> and allowing the application to instantiate the object only in heap
> using new operator. How to achieve this?
>
> I tried out with the following code.
> Could you please give me the reason for the compilation error for the
> following code:
>
> #include < iostream>
>
> class Temp
> {
> public:
> friend void* ::operator new (size_t);
> friend void ::operator delete (void* pDel);
> private:
> Temp ()
> {
> std::cout << "Temp Ctor" <<; }
> ~Temp ()
> {
> std::cout << "Temp Dtor" <<; }
> };
>
> int
> main ()
> {
> Temp *pT = new Temp;
> delete pT;
>
> // Temp tempObj; // Should be disallowed
> return 0;
> }
>
> Compilation error received:
> ---------------------------------------
> heap.cpp: In function 'int main()':
> heap.cpp:9: error: 'Temp::Temp()' is private
> heap.cpp:22: error: within this context
> heap.cpp:13: error: 'Temp::~Temp()' is private
> heap.cpp:23: error: within this context
>
> Please help me in instantiating the Temp object only in heap, not in
> stack.
>
> thanks
> Sukumar R
>

This code is overly complicated, to prevent object creation/destruction on stack, one just needs to declare a private destructor. Think about the life time of a stack object. It's created upon entrance of the function and destroyed before leaving the function. The compiler must have access to both constructors and destructor. It's inconvenient or maybe undesirable to declare private constructors but it's always straightforward to declare a private destructor.