copy of memorydiscard.cpp
来自「是内存受限系统设计的代码。」· C++ 代码 · 共 122 行
CPP
122 行
#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 + =
减小字号Ctrl + -
显示快捷键?