一. C++内存分配方法及new/delete源码
目录
一. C++内存分配工具
1. malloc()和free()
2. new和delete
3. ::operator new()和::operator delete()
4. allocator<T>::allocate()和allocator<T>::deallocate()
using namespace std;
//#include <bits/stdc++.h>
#include <iostream>
#include <complex>
#include <memory> //std::allocator
//#include <ext\pool_allocator.h> //欲使用 std::allocator 以外的 allocator, 就得自行 #include <ext/...>
#define __BORLANDC__
//#define
//malloc、new、operator new
int main() {
void* p1 = malloc(sizeof(int));
cout << p1 << endl;
free(p1);
complex<int>* p2 = new complex<int>;
cout << p2 << endl;
delete p2;
void* p3 = ::operator new(sizeof(int));
cout << p3 << endl;
::operator delete(p3);
//以下使用 C++ 標準庫提供的 allocators。
//其接口雖有標準規格,但實現廠商並未完全遵守;下面三者形式略異。
#ifdef _MSC_VER
//以下兩函數都是 non-static,定要通過 object 調用。以下分配 3 個 ints.
int* p4 = allocator<int>().allocate(3, (int*)0);
cout << p4 << endl;
allocator<int>().deallocate(p4, 3);
#endif
#ifdef __BORLANDC__
//以下兩函數都是 non-static,定要通過 object 調用。以下分配 5 個 ints.
int* p5 = allocator<int>().allocate(5);
cout << p5 << endl;
allocator<int>().deallocate(p5, 5);
#endif
#ifdef __GNUC__