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

📄 copy of 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;

    static TemporaryHeap* singletonInstance;

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


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

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

    void reset() {
        nBytesAllocated = 0;
    }

    static TemporaryHeap& theInstance() {
        assert(singletonInstance != 0);
        return *singletonInstance;
    }

    static void create(size_t theSize) {
        assert(singletonInstance == 0);
        assert(theSize != 0);
        singletonInstance = new TemporaryHeap( theSize );
    }
};

TemporaryHeap* TemporaryHeap::singletonInstance;


class TemporaryHeapObject  {
public:
    // Uses default ctor, dtor, copy ctor, op=

    void * operator new ( size_t heapSizeInBytes ) {
        return TemporaryHeap::theInstance().Allocate(heapSizeInBytes);
    }

    void operator delete ( void * ) { 
        assert( 0 ); 
    }
};


class IntermediateCalculationResult : public TemporaryHeapObject {
public: 
    IntermediateCalculationResult() : initialised( 1 ) {}
    ~IntermediateCalculationResult() { assert( 0 ); }
    void check() { assert( initialised ); }

private:
    bool initialised;
    char dummy[40];
};

int main() {
    TemporaryHeap::create( 100 );
    try {
        for (int i = 0; i<100; i++) {
            IntermediateCalculationResult* p = new IntermediateCalculationResult;
            p->check();
        }
        assert( 0 );
    }
    catch ( bad_alloc& ) {
    }
    TemporaryHeap::theInstance().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 + -