• code project 上的内存管理的示例代码


    /********************************************************************
        created:    2014/03/17 18:53
        filename:    main.cpp
        author:        Justme0 (http://blog.csdn.net/justme0)
    
        purpose:    code project 内存管理
    *********************************************************************/
    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    #include <new>
    using namespace std;
    
    //    Overload the new operator
    void *operator new ( size_t size , bool isAllocFailure )
    {
        if ( isAllocFailure )
            return NULL;
        else
        {
            try
            {
                void *Memory    =    ::operator new ( size );
                return Memory;
            }
            catch ( std::bad_alloc )
            {
                return NULL;
            }
        }
        return NULL;
    }
    
    //    Overload placement delete operator so that exceptions from
    //    constructors can be handled
    void operator delete ( void * Memory , bool isAllocFailure )
    {
        ::delete Memory;
    }
    
    void    SimpleFunction ( int MemCounter , bool AllFail )
    {
    
        int        LocalCounter = 0;
        char    *Mem1    =    new ( ( MemCounter == LocalCounter ++ ) || AllFail ) char [ 32 ];
        if ( Mem1 != NULL )
            strcpy ( Mem1 , "First Memory" );
    
        char    *Mem2    =    new ( ( MemCounter == LocalCounter ++ ) || AllFail ) char [ 32 ];
        if ( Mem2 != NULL )
            strcpy ( Mem2 , "Second Memory" );
    
        int        NumTimesLoop    =    10;
        int        LoopCounter        =    0;
    
        //    Create a Variable that will be allocate Inner Memory
        char    **InnerMemory    =    new ( ( MemCounter == LocalCounter ++ ) || AllFail ) char * [ NumTimesLoop ];
    
        //    Loop through and allocate the memory required    
        for ( LoopCounter = 0; LoopCounter < NumTimesLoop ; LoopCounter ++ )
        {
            InnerMemory [ LoopCounter ] = new ( ( MemCounter == LocalCounter ++ ) || AllFail ) char [ 32 ];
        }
    
    
    }
    
    
    int main()
    {
        for ( int counter = 0; counter < 12; counter ++ )
            SimpleFunction ( counter , false );
        SimpleFunction ( -1 , true );
    
        return 0;
    }
  • 相关阅读:
    当教育成为一种商品
    怎样设置Solaris上网
    对象转为xml输出到页面,中文乱码问题
    Flex 深拷贝与浅拷贝笔记
    使用access数据库需要注意的问题
    根据数据库表结构生成xsd文件
    SendKeys.Send()输入中文
    VB6迁移到VB.NET的一些问题汇总
    技术文章转移完毕
    说说重复发明轮子的事儿
  • 原文地址:https://www.cnblogs.com/jjtx/p/3605969.html
Copyright © 2020-2023  润新知