Re: friend operator new/delete - allow obj instantiation only in heap - howto?
On 25 Apr 2007 02:58:47 -0700, WittyGuy <wittyguysuku@gmail.com>
wrote:
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" << std::endl;
}
~Temp ()
{
std::cout << "Temp Dtor" << std::endl;
}
};
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
class Temp {
public:
~Temp() { ; }
auto_ptr<Temp> getInstance() { return new Temp; }
private:
Temp() { ; }
};