前言
根据侯捷大神的课所作的总结与实践,主要是理清思路,方便之后查阅。
C++应用程序使用memory的途径
如图所示,C++应用程序可从四个层面来进行内存分配。
- 使用C++标准库所提供的内存分配管理器allocator
- 使用C++基本函数new等
- 使用C语言中的malloc/free
- 调用操作系统内存分配的API
C++ memory primitives(内存分配基本工具)
test_primitives.h中使用了以上方法来分配内存.
#ifndef __TEST_PRIMITIVES_H__
#define __TEST_PRIMITIVES_H__
#include <iostream>
#include <complex>
#include <memory> //std::allocator
#include <ext/pool_allocator.h> //欲使用 std::allocator 以外的 allocator, 就得自行 #include <ext/...>
using namespace std;
namespace memo_test
{
void test_primitives()
{
cout << "\ntest_primitives().......... \n";
//使用C函数 malloc 和 free 分配内存
void* p1 = malloc(512); //512 bytes
free(p1);
//使用C++表达式 new 和 delete 分配内存
complex<int>* p2 = new complex<int>; //one object
delete p2;
//使用 :: operator new 来分配内存
void* p3 = ::operator new(512); //512 bytes
::operator delete(p3);
//以下使用 C++ 标准库提供的 allocators。来分配内存
//其接口雖有标准规格,但实际厂商并未完全遵守;下面三者形式略有不同。
#ifdef _MSC_VER
//以下两函数都是 non-static,定要通过 object 调用。以下分配 3 个 ints.
int* p4 = allocator<int>().allocate(3, (int*)0);
allocator<int>().deallocate(p4,3);
#endif
#ifdef __BORLANDC__
//以下两函数都是 non-static,定要通过 object 调用。以下分配 5 个 ints.
int* p4 = allocator<int>().allocate(5);
allocator<int>().deallocate(p4,5);
#endif
#ifdef __GNUC__
//以下兩函數都是 static,可通過全名調用。以下分配 512 bytes.
//void* p4 = alloc::allocate(512);
//alloc::deallocate(p4,512);
//以下兩函數都是 non-static,定要通過 object 調用。以下分配 7 個 ints.
void* p4 = allocator<int>().allocate(7);
allocator<int>().deallocate((int*)p4,7);
//以下兩函數都是 non-static,定要通過 object 調用。以下分配 9 個 ints.
//内存池分配方法
void* p5 = __gnu_cxx::__pool_alloc<int>().allocate(9);
__gnu_cxx::__pool_alloc<int>().deallocate((int*)p5,9);
#endif
}
} //namespace
#endif // !__TEST_PRIMITIVES_H__