C++:动态内存分配(new、delete 相比 malloc、free的优势)与运算符重载

动态内存分配与运算符重载

  • 一、动态内存分配
    • (一)内存的分类
    • (二)动态内存分配函数
      • (1)new 和delete 的使用
        • (1)new 的原理
        • (2)delete 的原理
      • 2、 operator new与operator delete
        • (1)operator new 的原理
        • (2)operator delete 的原理
    • (三)定位new
    • (四) malloc/free和new/delete的区别
  • 二、操作符重载
    • (一)输入输出重载
    • (二)其它操作符重载
      • 结束语

在这里插入图片描述

一、动态内存分配

(一)内存的分类

在C/C++中,内存主要分为五个部分,其中我们之前C语言学习过程中的动态内存分配读取的堆区的内存。
在这里插入图片描述

  1. 栈:非静态局部变量/函数参数/返回值等等,栈是向下增长的。
  2. 内存映射段:是高效的I/O映射方式,用于装载一个共享的动态内存库。用户可使用系统接口创建共享共享内存,做进程间通信。
  3. 堆:用于程序运行时动态内存分配,堆是向上增长的。
  4. 数据段:存储全局数据和静态数据
  5. 代码段:可执行代码、只读常量

(二)动态内存分配函数

(1)new 和delete 的使用

在动态内存分配是,通过控制台可以发现,堆区是向上增长的。同时也发现了new / deletemalloc / free 这组函数的区别,前者会申请后完成构造,释放时自动调用析构,而后者只做空间的申请

class A
{
public:A(int a = 0): _a(a){cout << "A():" << this << endl;}~A(){cout << "~A():" << this << endl;}
private:int _a;
};int main() {cout << "内置类型:" << endl;int* p1 = new int;int* p2 = new int(1);int* p3 = new int[3];delete p1;delete p2;delete[] p3;cout << "自定义类型:" << endl;A* p4 = new A;A* p5 = new A(1);A* p6 = new A[3];delete p4;delete p5;delete[] p6;return 0;
}

在这里插入图片描述

(1)new 的原理

通过汇编代码,可以清楚的发现,new 调用了 operator new 函数和构造函数
在这里插入图片描述

(2)delete 的原理

和new 一样,先调用了析构函数,后调用了 operater delete。
在这里插入图片描述

2、 operator new与operator delete

需要区分的是,new 和 delete是用户进行动态内存申请和释放的操作符,operator new operator delete是系统提供的全局函数,不是函数重载new在底层调用operator new来申请空间,delete在底层通过operator delete来释放空间。

(1)operator new 的原理

通过下面代码,我们可以发现,operate new也是通过 malloc 来申请空间,相比于 malloc,不再通过返回值是否为空来判断申请的成功与否,而是抛异常的方式。
而在参数上面二者一致。

void* __CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
{// try to allocate size bytesvoid* p;while ((p = malloc(size)) == 0)if (_callnewh(size) == 0){// report no memory// 如果申请内存失败了,这里会抛出bad_alloc 类型异常static const std::bad_alloc nomem;_RAISE(nomem);}return (p);
}
(2)operator delete 的原理

不难看出,delete 的底层也是采用free 实现,free 本质是一个宏。

void operator delete(void* pUserData)
{_CrtMemBlockHeader* pHead;RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));if (pUserData == NULL)return;_mlock(_HEAP_LOCK); __TRYpHead = pHdr(pUserData);_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));_free_dbg(pUserData, pHead->nBlockUse);__FINALLY_munlock(_HEAP_LOCK);__END_TRY_FINALLYreturn;
}#define free(p) _free_dbg(p, _NORMAL_BLOCK)

(三)定位new

如果我们想要将申请空间和构造函数、释放空间和析构函数分开调用,又该怎么办呢。我们知道构造函数不可以显示调用,此时可以用到定位new。

new (place_address) type或者new (place_address) type(initializer-list)
其中,place_address必须是一个指针,initializer-list是类型的初始化列表

A* object = (A*)malloc(sizeof(A));
new(object)A(1);
object->~A();
free(object);A* object2 = (A*)operator new(sizeof(A));
new(object2)A;
object2->~A();
free(object2);

在这里插入图片描述
在上面的代码中,采用mallocoperater new的唯一区别就是前者可以通过检查返回值查看是否开辟成功,而后者通过抛异常的方式检测。

(四) malloc/free和new/delete的区别

  1. malloc和free是函数,new和delete是操作符
  2. malloc申请的空间不会初始化,new可以初始化
  3. malloc申请空间时,需要手动计算空间大小并传递,new只需在其后跟上空间的类型,多个对象在[]中指定对象个数
  4. malloc的返回值为void*, 在使用时必须强转,new不需要
  5. malloc申请空间失败时,返回的是NULL,因此使用时必须判空,new不需要,但是new需要捕获异常
  6. 申请自定义类型对象时,malloc/free只会开辟空间,不会调用构造函数与析构函数,而new和delete会调用构造函数与析构函数

二、操作符重载

我们通过实现一个日期类来说明这部分知识。由于运算符重载并不复杂,挑选有特点的部分讲解。

运算符重载要点
1、可以利用运算符之间的联系来重载其它运算符。
2、对于不改变this 指针的运算符,可以考虑加上 const 否则一些const对象在调用时可能会造成权限的放大,导致错误

(一)输入输出重载

输入输出流重载中,只能写成全局函数。因为成员函数中存在隐藏的this 指针,而函数重载规定参数列表中的第一个参数是在运算符右边,如果写成成员函数就要反过来,老别扭了。

ostream& operator<<(ostream& out, const Date& d) 
{out << d._year << "年" << d._month << "月" << d._day << "日" << endl;return out;
}istream& operator>>(istream & in,  Date & d)
{while (1) {cout << "请输入年、月、日" << endl;in >> d._year >> d._month >> d._day;if (!d.check_date()) {cout << "日期不合法,请重新输入!" << endl;continue;}break;}return in;
}

(二)其它操作符重载

class Date {friend ostream& operator<<(ostream& out, const Date& data);friend istream& operator>>(istream& in,  Date& d);
public:Date(int year = 1, int month = 1, int day = 1);bool check_date() const;bool isRunNian() const;int getMonthDay(int month) const;void print_date() const;//比较运算符重载bool operator<(const Date& d) const;bool operator<=(const Date& d) const;bool operator>(const Date& d) const;bool operator>=(const Date& d) const;bool operator==(const Date& d) const;bool operator!=(const Date& d) const;//加减运算符重载Date& operator+=(int day);Date operator+(int day) const;Date& operator-=(int day);Date operator-(int day) const;int operator-(const Date& d) const;Date& operator++();Date operator++(int);Date& operator--();Date operator--(int);
private:int _year;int _month;int _day;static int _month_day[13];
};int Date::_month_day[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31 };Date::Date(int year, int month, int day):_year(year), _month(month), _day(day)
{if (!check_date()) {cout << "日期不合法!" << endl;}
}bool Date::check_date() const
{if (_month > 12 || _month < 1)return false;else if (_day > getMonthDay(_month) || _day < 1) return false;else return true;
}bool Date::isRunNian()const
{if ((_year % 4 == 0 && _year % 100 != 0) || _year % 400 == 0)return true;else return false;
}int Date::getMonthDay(int month) const
{if (month == 2) {if (isRunNian()) return 29;}return _month_day[month];
}void Date::print_date() const
{cout << _year << '-' << _month << '-' << _day << endl;
}bool Date::operator<(const Date& d) const 
{if (_year != d._year)return _year < d._year;else if (_month != d._month) return _month < d._month;else return _day < d._day;
}bool Date::operator<=(const Date& d) const
{return (*this < d || *this == d);
}
bool Date::operator>(const Date& d) const
{return !(*this <= d);
}
bool Date::operator>=(const Date& d) const
{return !(*this < d);
}
bool Date::operator==(const Date& d) const
{return _year == d._year && _month == d._month && _day == d._day;
}
bool Date::operator!=(const Date& d) const
{return !(*this == d);
}Date& Date::operator+=(int day)
{_day += day;while (_day > getMonthDay(_month)) {_day -= getMonthDay(_month);if (++_month == 13) {_month = 1;_year += 1;}}return *this;
}Date Date::operator+(int day) const
{Date object(*this);object += day;return object;
}Date& Date::operator-=(int day)
{_day -= day;while (_day < 1) {if (--_month == 0) {_month = 12;_year -= 1;}_day += getMonthDay(_month);}return *this;
}
Date Date::operator-(int day) const
{Date object(*this);object -= day;return object;
}int Date::operator-(const Date& d) const
{Date max = *this;Date min = d;int flag = 1;if (max < min) {max = d;min = *this;flag = -1;}int n = 0;while (min != max) {min += 1;n++;}return n;
}Date& Date::operator++()
{return (*this += 1);
}Date Date::operator++(int)
{Date temp(*this);*this += 1;return temp;
}Date& Date::operator--()
{return (*this -= 1);
}Date Date::operator--(int)
{Date temp(*this);*this -= 1;return temp;
}void test01()
{Date object1(2024, 2, 29);Date object2(2024, 2, 18);Date object3(2024, 2, 18);if (object1 > object2) cout << "object1 < object2" << endl;if (object3 == object2) cout << "object3 == object2" << endl;
}ostream& operator<<(ostream& out, const Date& d) 
{out << d._year << "年" << d._month << "月" << d._day << "日" << endl;return out;
}istream& operator>>(istream & in,  Date & d)
{while (1) {cout << "请输入年、月、日" << endl;in >> d._year >> d._month >> d._day;if (!d.check_date()) {cout << "日期不合法,请重新输入!" << endl;continue;}break;}return in;
}void test02()
{Date object1(1940, 10, 5);Date object2(2024, 8, 27);Date object3(2024, 9, 19);Date object4(2004, 7, 19);object4 += 7367;object4.print_date();object3 -= 7367;object3.print_date();cout << object3 - object4 << endl;cout << object2 - object1 << endl;object1++;object1.print_date();object1--;object1.print_date();

结束语

小伙伴们,文章就先告一段落了,感谢各位长期以来的支持,博主就先撤啦!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/144454.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

地图资源下载工具失效下载链接重新分享

今天发现地图资源工具下载链接被失效了&#xff0c;也不知道为啥&#xff01;不过不影响啥&#xff0c;我再分享一下就行&#xff01;请关注我的公众号及博客以便及时了解最新下载及更新信息&#xff01;另外如遇到工具分享链接失效或不能下载的情况可私信我&#xff0c;我会第…

69.x的平方根 (Java)20240919

问题描述&#xff1a; java代码&#xff1a; class Solution {public int mySqrt(int x) {if (x < 2) {return x; // 0 和 1 的平方根分别是它们自己}int left 2; // 从2开始&#xff0c;因为0和1已经处理了int right x / 2; // 最大可能的平方根不会超过 x / 2int mid;w…

基于单片机的智能家居控制系统设计

本设计 基于WiFi的智能家居系统的设计&#xff0c;主要包括主控芯片、WiFi通讯模块、CO传感器、液位传感器、温度传感器、烟雾传感器、火焰传感器、蜂鸣器模块、继电器模块等。通过各传感器实时采集家里的环境&#xff0c;并将数据发送至单片机STM32F030C8T6&#xff0c;单片机…

97、prometheus之yaml文件

命令回顾 [rootmaster01 ~]# kubectl explain ingressKIND: Ingress VERSION: networking.k8s.io/v1DESCRIPTION:Ingress is a collection of rules that allow inbound connections to reachthe endpoints defined by a backend. An Ingress can be configured to givese…

Day.js时间插件的安装引用与常用方法大全

&#x1f680; 个人简介&#xff1a;某大型国企资深软件研发工程师&#xff0c;信息系统项目管理师、CSDN优质创作者、阿里云专家博主&#xff0c;华为云云享专家&#xff0c;分享前端后端相关技术与工作常见问题~ &#x1f49f; 作 者&#xff1a;码喽的自我修养&#x1f9…

kafka之路-01从零搭建环境到SpringBoot集成

kafka之路-01从零搭建环境到SpringBoot集成 原创 今夜写代码 今夜写代码 2024年07月21日 21:58 浙江 一、kafka 架构简单介绍 1) 生产者将消息发送到Broker 节点&#xff0c;消费者从Broker 订阅消息 2&#xff09;消息订阅通常有服务端Push 和 消费端Pull两种方式&#xff…

家用小型洗衣机哪个牌子好?五款热搜爆火型号,速来围观

在日常生活中&#xff0c;内衣洗衣机已成为现代家庭必备的重要家电之一。选择一款耐用、质量优秀的内衣洗衣机&#xff0c;不仅可以减少洗衣负担&#xff0c;还能提供高效的洗涤效果。然而&#xff0c;市场上众多内衣洗衣机品牌琳琅满目&#xff0c;让我们往往难以选择。那么&a…

【JavaEE】多线程编程引入——认识Thread类

阿华代码&#xff0c;不是逆风&#xff0c;就是我疯&#xff0c;你们的点赞收藏是我前进最大的动力&#xff01;&#xff01;希望本文内容能帮到你&#xff01; 目录 引入&#xff1a; 一&#xff1a;Thread类 1&#xff1a;Thread类可以直接调用 2&#xff1a;run方法 &a…

K8S容器实例Pod安装curl-vim-telnet工具

在没有域名的情况下&#xff0c;有时候需要调试接口等需要此工具 安装curl、telnet、vim等 直接使用 apk add curlapk add vimapk add tennet

Python编码系列—Python工厂方法模式:构建灵活对象的秘诀

&#x1f31f;&#x1f31f; 欢迎来到我的技术小筑&#xff0c;一个专为技术探索者打造的交流空间。在这里&#xff0c;我们不仅分享代码的智慧&#xff0c;还探讨技术的深度与广度。无论您是资深开发者还是技术新手&#xff0c;这里都有一片属于您的天空。让我们在知识的海洋中…

【深度学习】初识神经网络

神经网络的表示 一个简单的两层神经网络如下图所示&#xff0c;每个圆圈都代表一个神经元&#xff0c;又名预测器。 一个神经元的计算详情如下。在我们原本输入的变量x的基础上&#xff0c;还有权重w和偏置b&#xff1b;在计算z过后&#xff0c;再将其带入sigmoid激活函数&…

招行 CBS8银企直连 前置机对接技术指南

引言 集团企业在使用CBS财资系统之后&#xff0c;如需构建企业自身ERP系统与CBS财资系统数据互通&#xff0c;可选择前置方式做数据中转&#xff0c;解决客户系统与CBS财资系统进行数据交换过程中的特殊需求。CBSLink&#xff08;即&#xff1a;前置机&#xff09;仍通过OpenAP…

10 vue3之全局组件,局部组件,递归组件,动态组件

全局组件 使用频率非常高的组件可以搞成全局组件&#xff0c;无需再组件中再次import引入 在main.ts 注册 import Card from ./components/Card/index.vuecreateApp(App).component(Card,Card).mount(#app) 使用方法 直接在其他vue页面 立即使用即可 无需引入 <templat…

.NET 音频播放器 界面优雅,体验流畅

目录 前言 项目介绍 项目页面 用户界面与动画效果 音频格式支持与封面模式 任务栏模式 歌词功能 更多功能探索 项目源码 项目地址 前言 本文介绍一款使用 C# 与 WPF 开发的音频播放器&#xff0c;其界面简洁大方&#xff0c;操作体验流畅。该播放器支持多种音频格式&…

UDS协议介绍-------28服务

功能描述 根据ISO14229-1标准中所述&#xff0c;诊断服务28服务主要用于网络中的报文发送与接收&#xff0c;例如控制应用报文的发送与接收&#xff0c;又或是控制网络管理报文的发送与接收。 应用场景 对于28诊断服务&#xff0c;主要应用场景为以下场合&#xff1a; 1、存…

eclipse git 不小心点了igore,文件如何加到git中去。

1、创建了文件&#xff0c;或者利用三方工具&#xff0c;或者用mybatis plus生成了文件以后&#xff0c;我们需要右键文件&#xff0c;然后加入到git中。 右键有问号的java文件 -- Team -- Add to Index &#xff0c;然后变成个号就可以了。 2、不小心&#xff0c;点了一下Ign…

Navicat如何实现Excel表格内数据导入数据库?

Navicat-MySQL数据导入 数据已被写在excel内&#xff0c;对应字段对应数据 找到需要导数据的表&#xff0c;右击改表选择仅结构的复制&#xff0c;复制出的新表和旧表字段相等结构相同 右击新表选择导入向导进行数据的导入&#xff0c;我采用excel表的方式进行导入 选择自己数…

电子看板实时监控数据可视化助力工厂精细化管理

在当今竞争激烈的制造业领域&#xff0c;工厂的精细化管理成为提高竞争力的关键。而电子看板实时监控数据可视化作为一种先进的管理工具&#xff0c;正为工厂的精细化管理带来巨大的助力。 一、工厂精细化管理的挑战 随着市场需求的不断变化和客户对产品质量要求的日益提高&am…

OpenCV运动分析和目标跟踪(4)创建汉宁窗函数createHanningWindow()的使用

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 此函数计算二维的汉宁窗系数。 createHanningWindow是OpenCV中的一个函数&#xff0c;用于创建汉宁窗&#xff08;Hann window&#xff09;。汉宁…

零基础制作一个ST-LINK V2 附PCB文件原理图 AD格式

资料下载地址&#xff1a;零基础制作一个ST-LINK V2 附PCB文件原理图 AD格式 ST-LINK/V2是一款可以在线仿真以及下载STM8以及STM32的开发工具。支持所有带SWIM接口的STM8系列单片机;支持所有带JTAG / SWD接口的STM32系列单片机。 基本属性 ST-LINK/V2是ST意法半导体为评估、开…