乐趣区

关于c++:More-Effective-C技术篇要求或禁止对象产生于heap之中

  • 要求对象产生于 heap 中,意思是须要阻止 clients 不得应用 new 以外的办法产生对象。比拟好的办法就是将 destructor 定义为 private,因为 constructor 的类型太多,所以依然将 constructor 定义为 public。而后定义一个 pseudo destructor 来调用真正的 destructor。示例如下:

    class HeapBasedObject {
    public:
      HeapBasedObject() {}
      void destroy() const { delete this;} // pseudo destructor
    
    private:
      ~HeapBasedObject() {}
    };
    
    int main()
    {
      //HeapBasedObject h;
      HeapBasedObject *ph = new HeapBasedObject;
      //delete ph;
      ph->destroy();}
  • 禁止对象产生于 heap 中,则是要让 clients 不能应用 new 办法来产生对象。办法就是将 operator new 和 operator delete 定义为 private。示例如下:

    #include <stdlib.h>
    
    class NoHeapBasedObject {
    public:
      NoHeapBasedObject() {}
      ~NoHeapBasedObject() {}
    
    private:
      static void *operator new(size_t size) {}
      static void operator delete(void *ptr) {}};
    
    int main()
    {
      NoHeapBasedObject nh;
      static NoHeapBasedObject snh;
      //NoHeapBasedObject *pnh = new NoHeapBasedObject;
    }
  • 下例是实现的一个判断某个对象是否位于 heap 内的基类 HeapTracked。

    #include <stdlib.h>
    #include <list>
    #include <iostream>
    
    class HeapTracked {
    public:
      class MissingAddress{}; // 地址异样
      virtual ~HeapTracked() = 0;
    
      static void *operator new(size_t size);
      static void operator delete(void *ptr);
    
      bool isOnHeap() const;
    
    private:
      typedef const void* RawAddress;
      static std::list<RawAddress> addresses;
    };
    
    std::list<HeapTracked::RawAddress> HeapTracked::addresses;
    
    HeapTracked::~HeapTracked() {}
    
    void* HeapTracked::operator new(size_t size) {void* memPtr = ::operator new(size); // 获得内存。addresses.push_front(memPtr); // 将其地址置于 list 头部。return memPtr;
    }
    
    void HeapTracked::operator delete(void *ptr) {auto it = std::find(addresses.begin(), addresses.end(), ptr);
    
      if (it != addresses.end()) {addresses.erase(it);
          ::operator delete(ptr);
      } else {throw MissingAddress();
      }
    }
    
    bool HeapTracked::isOnHeap() const {auto rawAddress = dynamic_cast<const void*>(this);
    
      auto it = std::find(addresses.begin(), addresses.end(), rawAddress);
      
      return it != addresses.end();}
    
    class Object: public HeapTracked {
    public:
      Object() {}
      ~Object() {}
    };
    
    
    int main()
    {
      Object o1;
      Object* o2 = new Object;
      std::cout << "o1 isOnHeap =" << o1.isOnHeap() << std::endl;
      std::cout << "o2 isOnHeap =" << o2->isOnHeap() << std::endl;}
退出移动版