zoukankan      html  css  js  c++  java
  • C++重载new delete

    #include <iostream>
    #include <cstdlib>
    using namespace std;
    class Foo{
        private:
            int _id;
        public:
            Foo(int id):_id(id){
                cout<<"Foo(int id) id:"<<id<<endl;
            }
            Foo():_id(0){
                
            };
        static void*  operator new(size_t size){
            void *ptr;
            cout<<"new size:"<<size<<endl;        
            ptr = malloc(size);
            cout<<"new ptr:"<<ptr<<endl;
            return ptr;
           }
        static void* operator new[] (size_t size){
              cout<<"new [] size:"<<size<<endl;
              return malloc(size);
          }
        static void operator delete (void *ptr, size_t size){
            cout<<"delete size:"<<size<<endl;
            cout<<"delete ptr:"<<ptr<<endl;
            free(ptr);
        }
        static void operator delete [](void *ptr, size_t size){
            cout<<"delete [] size :"<<size<<endl;
            free(ptr);
        }
    };
    int main(){
        
        Foo *p = new Foo(2);
        delete p;
        cout<<"------------------"<<endl;
        Foo* ptr = new Foo[3];
        delete []ptr;
        cout<<endl;
        return 0;
    }
    

    输出:
    new size:4
    new ptr:0x315a0
    Foo(int id) id:2
    delete size:4
    delete ptr:0x315a0
    ------------------
    new [] size:16
    delete [] size :16

  • 相关阅读:
    Android之帧动画2
    CSS之图片关闭
    JAVA之While语句、Do和For语句
    oracle 无效字符
    java 时间制
    mybatis jdbcType date没有时分秒
    log4j说明
    spy 日志说明
    linux更新系统时间
    linux常用命令2
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12537757.html
Copyright © 2011-2022 走看看