一. C++内存分配方法、new/delete源码及new模拟

本文详细介绍了C++中的内存分配工具,包括malloc/free、new/delete、operator new()和operator delete(),以及allocator的allocate/deallocate。深入探讨了new和delete的源码实现,揭示了它们与malloc/free的关系。同时,文章还通过仿照侯捷的源码模拟了new/delete操作的过程。
摘要由CSDN通过智能技术生成

一. C++内存分配方法及new/delete源码

目录

一. C++内存分配方法及new/delete源码

一. C++内存分配工具

二. 内存分配工具间关系

三. new/delete源码

new源码

delete源码

四. 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__
 
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值