C++"准中级"技术(类唯一实例,只能在堆中创建对象,重写operator new和operator delete)实现

类别:编程语言 点击:0 评论:0 推荐:

#include <windows.h>
#include <iostream>
using namespace std;
class A
{
public:
 static A* Create()
 {
  if (m_IsAlreadyCreated)
   return (A*)0;
  else
  {
   return (A*)(operator new (sizeof(A)));
  }
 }

 static void* operator new (size_t size)
 {
  if (m_IsAlreadyCreated)
   return (void*)0;

  if (size != sizeof(A))
  {
   /*********************************************
   解决办法一:
   void* pNew = 0;
   pNew = ::operator new(size);//注意,这里不会调用类A的构造函数,所以我没有采纳,以后或许有更好的办法.
   if (pNew)
   {
    m_IsAlreadyCreated = true;
   }
   return pNew;
   **********************************************/
   return (void*)0;
  }

  A* pA = (A*)::malloc(size);
  if (pA)
  {
   pA->A::A();
  }
  return pA;
 }

 static void operator delete(void* pData,size_t size)
 {
  if (!pData || !m_IsAlreadyCreated)
   return ;

  if (size != sizeof(A))
  {
   /*********************************************
   解决办法一:
   ::operator delete(pData);//注意,这里不会调用类A的析构函数,所以我没有采纳,以后或许有更好的办法.
   m_IsAlreadyCreated = false;
   **********************************************/
   throw;/*暂时抛出异常*/
   return ;
  }
  else
  {
   A* pA = (A*)pData;
   pA->A::~A();
   ::free(pData);
  }
 }

 void Delete()
 {
  if (m_IsAlreadyCreated)
   operator delete(this,sizeof(A));
 }
 ~A()
 {
  m_IsAlreadyCreated = false;
  cout << "Destruction A" << endl;
 }
private:
 A()
 {
  m_IsAlreadyCreated = true;
  cout << "Construction A" << endl;
 }
 A(A&){}
 static bool m_IsAlreadyCreated;
};
bool A::m_IsAlreadyCreated = false;

int main()
{
 //A a; //error;
 //A* pa = new A; //error;
 {
  A* pA = (A*)(A::operator new(sizeof(A)));
  pA->Delete();
 }

 {
  A* pA = A::Create();
  pA->Delete();
 }

 {
  A* pA = (A*)(A::operator new(sizeof(A)));
  A::operator delete(pA,sizeof(A));
 }

 {
  A* pA = (A*)(A::operator new(sizeof(A)));
  delete pA;
 }

 {
  A* pA = (A*)(A::operator new(sizeof(A)));
  A::operator delete(pA,sizeof(A)+sizeof(A));
 }
 return 0;
}

本文地址:http://com.8s8s.com/it/it22517.htm