⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 restricted.cpp

📁 内存受限系统软件开发一书的代码。(虽不及Gang of Four的模式掷地有声
💻 CPP
字号:

#include <New>
#include <iostream.h>
#include <assert.h>
#include <malloc.h>

#define ASSERT( x ) assert( x );

using namespace std;

 class MemoryRestrictedClass {
    int dataMember;
public:
    enum { LIMIT_IN_BYTES = 100 };
    static size_t totalMemoryCount;

    void* operator new ( size_t aSize );
    void operator delete( void* anItem, size_t aSize );

    /* Broken in VC++
       void* operator new[] ( size_t aSize ) { 
       if ( totalMemoryCount + aSize > LIMIT_IN_BYTES ) 
       throw ( bad_alloc() );
       totalMemoryCount += aSize; 
       return malloc( aSize );
       }
       void operator delete[]( void* anItem, size_t aSize ) {
       totalMemoryCount -= aSize; 
       free( (char*)anItem ); 

       }
    */
};

size_t MemoryRestrictedClass::totalMemoryCount = 0;

void* MemoryRestrictedClass::operator new ( size_t aSize ) { 
    if ( totalMemoryCount + aSize > LIMIT_IN_BYTES ) 
        throw ( bad_alloc() );
    totalMemoryCount += aSize; 
    return malloc( aSize );
}
void MemoryRestrictedClass::operator delete( void* anItem, size_t aSize ) {
    totalMemoryCount -= aSize; 
    free( (char*)anItem ); 
}


const int EXPECTED_ALLOCATIONS = 
MemoryRestrictedClass::LIMIT_IN_BYTES / sizeof( MemoryRestrictedClass );

int main()
{
    {
        int i;

        MemoryRestrictedClass* p[MemoryRestrictedClass::LIMIT_IN_BYTES * 2];
        try {
            for (i=0; i<(EXPECTED_ALLOCATIONS * 2); i++)
                { p[i] = new MemoryRestrictedClass; }
            ASSERT( 0 );
        } catch (bad_alloc x) {
        }
        ASSERT( MemoryRestrictedClass::LIMIT_IN_BYTES -
                MemoryRestrictedClass::totalMemoryCount < sizeof
                ( MemoryRestrictedClass ) );

        for (int j=0; j<i; j++)
            { delete p[j]; }
        ASSERT( MemoryRestrictedClass::totalMemoryCount == 0 );
    } 
    /* Broken in VC++ 5.0
       {
       int i;
       MemoryRestrictedClass* p[EXPECTED_ALLOCATIONS];
       try {
       for (i=0; i<EXPECTED_ALLOCATIONS; i++)
       { p[i] = new MemoryRestrictedClass[2]; }
       ASSERT( 0 );
       } catch (bad_alloc x) {
       }
       ASSERT( MemoryRestrictedClass::LIMIT_IN_BYTES -
       MemoryRestrictedClass::totalMemoryCount < 2*sizeof
       ( MemoryRestrictedClass ) );

       for (int j=0; j<i; j++)
       { delete []p[j]; }
       assert( MemoryRestrictedClass::totalMemoryCount == 0 );
       }
    */
    cout << "Successful\n";
    cin.get();
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -