分配器.pro
TEMPLATE = app
CONFIG += console c++17
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += \
main.cpp \
allocuser.cpp
HEADERS += \
allocuser.h
分配用户.h
#ifndef ALLOCUSER_H
#define ALLOCUSER_H
#include <bitset>
using namespace std;
class AllocUser
{
private:
public:
AllocUser();
const static int maxItem = 1000;
const static int maxSize = 32;
static std::bitset<maxItem> bufmap;
static inline char buf[maxItem * maxSize];
static int freeblock;
template <typename T>
static T *allocate(void) {
int i;
static_assert( sizeof(T) < AllocUser::maxSize, "Max size for this allocator excessed " );
for(i=AllocUser::freeblock; i<AllocUser::maxItem; i++) {
if( !AllocUser::bufmap.test(i) )
break;
}
if( i==AllocUser::maxItem ) throw new bad_alloc();
AllocUser::bufmap.set(i, true);
AllocUser::freeblock=i+1;
return static_cast<T*> (new (&buf[AllocUser::maxSize*i]) T());
}
template <typename T>
static void deallocate(T *ptr) {
int i = ( ((char*)ptr)-&buf[0] )/maxSize;
// if( !bufmap.test(i) ) throw new logic_error("Wrong deallocate");
ptr->~T();
bufmap.set(i, false);
if( freeblock > i ) freeblock=i;
}
};
#endif // ALLOCUSER_H
分配用户.cpp
#include "allocuser.h"
using namespace std;
AllocUser::AllocUser()
{
std::bitset<maxItem> bufmap;
}
主文件
#include <iostream>
#include <allocuser.h>
#define MAX_SZ 32
#define MAX_ITEM 1000
using namespace std;
int AllocUser::freeblock=0;
int main()
{
cout << "Hello World!" << endl;
// AllocUser *allocu = new AllocUser ();
// int allocu->freeblock=0;
for(long i=0; i<1000; i++) {
for(int j=0; j<3; j++){
int *a = AllocUser::allocate<int>();
*a=5;
AllocUser::deallocate( a );
}
}
return 0;
}
我看不出与某些“模板”有任何关系-您的课程不是模板课程。在大多数情况下,像往常一样,没有
std::bitset<maxItem> bufmap;.或者在
.cpp文件中添加定义或者(更简单的修复) - 在类定义中,做
这同样适用于所有其他静态字段,除了
const int字段。也不清楚你为什么要申请
static_cast<T*>一个已经有 type 的指针T *。