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

📄 memorydiscard.cpp

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

#include <stdlib.h>
#include <assert.h>
#include <iostream.h>

void* operator new( size_t /*heapSizeInBytes*/, void* memorySpace ) { 
    return memorySpace; 
}


class bad_alloc /*: public exception */{
public:
    bad_alloc() throw() {}
    bad_alloc(const bad_alloc&) throw() {}
    // bad_alloc& operator=(const bad_alloc&) throw();
    virtual ~bad_alloc() throw() {}
    virtual const char* what() const throw() { return "alloc"; }
};


class TemporaryHeap {
private:
    size_t nBytesAllocated;
    size_t heapSizeInBytes;
    char* heapMemory;

public:
    TemporaryHeap::TemporaryHeap( size_t heapSize);
    TemporaryHeap::~TemporaryHeap();
    void * TemporaryHeap::Allocate(size_t sizeOfObject);
    void TemporaryHeap::Reset();
};

TemporaryHeap::TemporaryHeap( size_t heapSize) 
    : heapSizeInBytes( heapSize )  {
    heapMemory = new char[heapSizeInBytes];
    Reset();
}

TemporaryHeap::~TemporaryHeap() { 
    delete[] heapMemory; 
}
    
void * TemporaryHeap::Allocate(size_t sizeOfObject) {
    if (nBytesAllocated + sizeOfObject >= heapSizeInBytes)
        throw bad_alloc();

    void *allocatedCell = heapMemory + nBytesAllocated;
    nBytesAllocated += sizeOfObject;
    return allocatedCell;
}

void TemporaryHeap::Reset() {
    nBytesAllocated = 0;
}


void * operator new ( size_t heapSizeInBytes, TemporaryHeap& theHeap ) {
    return theHeap.Allocate( heapSizeInBytes );
}

class IntermediateCalculationResult {
    char dummy[40];
};

int main() {
    TemporaryHeap theHeap( 100 );
    assert( new IntermediateCalculationResult );
    try {
        for (int i = 0; i<100; i++) {
            IntermediateCalculationResult* p =
                new( theHeap ) IntermediateCalculationResult;
        }
        assert( 0 );
    }
    catch ( bad_alloc& ) {
    }
    theHeap.Reset();
    assert( new IntermediateCalculationResult );

    cout<<"Tests succeeded"<<endl;
    cin.get(); cin.get();
    return 0;
}

void* HeapAlloc( void*, size_t ) { return 0; }
void* temporaryHeap;
class MyClass {};

void Dummy() {
    void* allocatedMemory = HeapAlloc( temporaryHeap, sizeof( MyClass ) );
    MyClass* pMyClass = new( allocatedMemory ) MyClass;
}

⌨️ 快捷键说明

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