zoukankan      html  css  js  c++  java
  • new 和 delete 运算符

    C++ 支持使用操作符 newdelete 来动态分配和释放对象。

    new 运算符调用特殊函数 operator newdelete 运算符调用特殊函数 operator delete

    如果 new 分配内存失败,异常 std::bad_alloc会被抛出。

    可以如下测试内存分配失败的情况:

    #include <iostream>
    using namespace std;
    #define BIG_NUMBER 100000000
    int main() {
       int *pI = new int[BIG_NUMBER];
       if( pI == 0x0 ) {
          cout << "Insufficient memory" << endl;
          return -1;
       }
    }
    

    使用 new 操作符动态分配的内存可以通过 delete 操作符进行释放。
    delete 操作符会触发调用类的析构函数(如果有的话)。

    以下示例为用户自定义的 operator newoperator delete

    #include <iostream>
    using namespace std;
    
    int fLogMemory = 0;      // Perform logging (0=no; nonzero=yes)?
    int cBlocksAllocated = 0;  // Count of blocks allocated.
    
    // User-defined operator new.
    void *operator new( size_t stAllocateBlock ) {
       static int fInOpNew = 0;   // Guard flag.
    
       if ( fLogMemory && !fInOpNew ) {
          fInOpNew = 1;
          clog << "Memory block " << ++cBlocksAllocated
              << " allocated for " << stAllocateBlock
              << " bytes
    ";
          fInOpNew = 0;
       }
       return malloc( stAllocateBlock );
    }
    
    // User-defined operator delete.
    void operator delete( void *pvMem ) {
       static int fInOpDelete = 0;   // Guard flag.
       if ( fLogMemory && !fInOpDelete ) {
          fInOpDelete = 1;
          clog << "Memory block " << cBlocksAllocated--
              << " deallocated
    ";
          fInOpDelete = 0;
       }
    
       free( pvMem );
    }
    
    int main( int argc, char *argv[] ) {
       fLogMemory = 1;   // Turn logging on
       if( argc > 1 )
          for( int i = 0; i < atoi( argv[1] ); ++i ) {
             char *pMem = new char[10];
             delete[] pMem;
          }
       fLogMemory = 0;  // Turn logging off.
       return cBlocksAllocated;
    }
    

    上述代码可以用来检测内存泄漏,重新定义全局操作符 newdelete 来计算内存的分配和释放次数。

    编译器支持在类中声明成员数组 newdelete 操作符:

    class X  {
    public:
       void * operator new[] (size_t) {
          return 0;
       }
       void operator delete[] (void*) {}
    };
    
    void f() {
       X *pX = new X[5];
       delete [] pX;
    }
    
  • 相关阅读:
    修改git提交的用户名和密码
    并发编程大师系列之:wait/notify/notifyAll/condition
    并发编程大师系列之:Synchronized的类锁和对象锁
    并发编程大师系列之:线程的定义和中断 interrupt
    SpringBoot项目mysql配置文件密码加密(jasypt)
    Linux下安装nginx实现伪分布
    idea远程debug调试阿里云ECS
    使用docker简单启动springboot项目
    用Navicat连接阿里云ECS服务器上的MySQL数据库
    Linux下安装JDK1.8
  • 原文地址:https://www.cnblogs.com/Steven-HU/p/14395584.html
Copyright © 2011-2022 走看看