STL字节对齐分配策略

今天无意中看了一下STL,发现STL中的空间配置器有两个等级,第一等级用malloc和free管理,第二等级用内存池管理,而内存池管理默认对齐字节数为8字节,发现一个很值得参考的代码,我简单的测试了一下:

 

 


<span style="font-size:18px;">// stl_alloc_test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
using namespace std;

#define _ALIGNSIZE 8

//这是STL 源码中的分配内存时用的策略
int my_alloc(size_t size)
{
	return ((size+_ALIGNSIZE-1) & ~(_ALIGNSIZE-1));
}
//这是我自己实现的策略
int my_alloc_2(size_t size)
{
	if (size % _ALIGNSIZE ==0)
	{
		return size;
	}
	else
	{
		return ((size/_ALIGNSIZE)+1)*_ALIGNSIZE;
	}
}
int _tmain(int argc, _TCHAR* argv[])
{

	cout<<my_alloc(31)<<endl;
	cout<<my_alloc_2(31)<<endl;
	system("pause");
	return 0;
}

</span>


 

 

 

你可能感兴趣的:(C++)