当前位置: 首页 > news >正文

c++中的匿名对象及内存管理及模版初阶

c++中的匿名对象

A a;//a的生命周期在整个main函数中
a.Sum(1);
//匿名对象生命周期只有一行,只有这一行会创建对象,出了这一行就会调析构
A().Sum(1);//只有这一行需要这个对象,其他地方不需要。
return 0;

日期到天数的转换 

计算日期到天数转换_牛客题霸_牛客网根据输入的日期,计算是这一年的第几天。 保证年份为4位数且日期合法。 进阶:时。题目来自【牛客题霸】icon-default.png?t=N7T8https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded?tpId=37&&tqId=21296&rp=1&ru=/activity/oj&qru=/ta/huawei/question-ranking

深入理解析构

#include <iostream>
#include <vector>
using namespace std;int main() {//vector<int> getMouthDays{0,31,28,31,30,31,30,31,31,30,31,30,31};static int getMouthDays[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };int year,mouth,day;while(cin>>year>>mouth>>day){int n=0;for(int i=1;i<mouth;++i){n+=getMouthDays[i];}n+=day;if(mouth>2&&((year%4==0&&year%100!=0)||(year%400==0)))n++;cout<<n<<endl;;}return 0;
}
// 64 位输出请用 printf("%lld")
C c;
int main()
{A a;B b;static D d;return 0;
}

构造顺序:C A B D

析构顺序:B A D C

static 修饰后(局部静态对象)第一次执行时才会调用构造 (初始化)。

全局的在main函数之前构造。

局部对象先析构,全局对象和静态对象在析构。

static D d;程序结束时才会销毁。

深入理解拷贝构造

 拷贝构造也是构造,写了拷贝构造编译器就不会生成构造了。

Widget v(u);
Widget w=v;

Widget w=v;

w存在:调operator赋值

w不存在:调拷贝构造

编译器不优化一个f(x) 调四次拷贝构造。最后共9次。

 内存管理

int globalVar = 1;static int staticGlobalVar = 1;void Test(){static int staticVar = 1;int localVar = 1;int num1[10] = {1, 2, 3, 4};char char2[] = "abcd";char* pChar3 = "abcd";int* ptr1 = (int*)malloc(sizeof (int)*4);int* ptr2 = (int*)calloc(4, sizeof(int));int* ptr3 = (int*)realloc(ptr2, sizeof(int)*4);free (ptr1);free (ptr3);}

char2是一个5个字节的数组整个数组都存在栈上。

全局变量和static变量的区别;

 链接属性不同

int globalVar = 1;static int staticGlobalVar = 1;

 执行main函数前就完成初始化。

    static int staticVar = 1;

当前文件可见 

int globalVar = 1;

 所有文件可见

运行到这个位置就初始化。

int globalVar = 1;

malloc/calloc/realloc的区别

malloc:申请空间

calloc:申请空间+初始化为0

realloc:对以有的空间进行扩容

int* p1=new int(10);
int* p2=new int[10];delete p1;
delete[] p2;

new和delete的意义?

对于内置类型申请的效果是一样的

对于自定义类型来说有区别

A* a = new A;//申请空间+调构造函数初始化
A* a2 = (A*)malloc(sizeof(A));
cout << a->_a << endl;
cout << a2->_a << endl;

delete a;//释放空间+调析构函数

operator new与operator delete函数

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

/*
operator 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);
}
 
/*
operator delete: 该函数最终是通过free来释放空间的
*/
void operator delete(void *pUserData)
{_CrtMemBlockHeader * pHead;RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));if (pUserData == NULL)return;_mlock(_HEAP_LOCK); /* block other threads */__TRY/* get a pointer to memory block header */pHead = pHdr(pUserData);/* verify block type */_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));_free_dbg( pUserData, pHead->nBlockUse );__FINALLY_munlock(_HEAP_LOCK); /* release other threads */__END_TRY_FINALLYreturn;
}/*
free的实现
*/
#define free(p) _free_dbg(p, _NORMAL_BLOCK)

对比malloc和new operator

    size_t size=2;void* p4=malloc(size*1024*1024*1024);cout<<p4<<endl;

malloc申请失败返回0

	try{void* p5=operator new(2*1024*1024*1024);cout<<p5<<endl;		}catch(exception& e){cout<<e.what()<<endl;}

使用方式一样处理错误方式不一样。

new operator更符合面向对象的方式。

 

 定制operator new 和 operator delete

void* operator new(size_t n){void* p = nullptr;p = allocator<ListNode>().allocate(1);cout << "memory pool allocate" << endl;return p;}void operator delete(void* p){allocator<ListNode>().deallocate((ListNode*)p, 1);cout << "memory pool deallocate" << endl;}
};

定位new/replacement new

对已经存在的一块空间调用构造函数初始化

	A* p2=(A*)operator new(sizeof(A));new(p2)A(10);p2->~A();operator delete(p2);

格式:new(空间指针)类型参数

int的范围 -2^31-2^32-1

申请4G空间

x64:

	size_t size=2;
//	void* p4=malloc(size*1024*1024*1024);
//	cout<<p4<<endl; 
//	try{char* p5= new char[2*1024*1024*1024];cout<<p5<<endl;		}catch(exception& e){cout<<e.what()<<endl;}

模版初阶 

函数模版 

目录

c++中的匿名对象

日期到天数的转换 

深入理解析构

深入理解拷贝构造

 内存管理

全局变量和static变量的区别;

malloc/calloc/realloc的区别

new和delete的意义?

operator new与operator delete函数

对比malloc和new operator

 定制operator new 和 operator delete

定位new/replacement new

模版初阶 

函数模版 


template<class T>
void Swap(T& x1,T&x2)
{T x=x1;x1=x2;x2=T;
}

我们不能调用函数模版,调用的是函数模版实例化生成的对应类型的函数

 预处理时生成。

 

 

 

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 【自用16.】C++类
  • 组合式API-reactive和ref函数,computed计算属性,watch函数
  • Linux和Unix的区别及为什么鸿蒙系统不用Unix的原因
  • 排序算法(冒泡、插入、选择、快排、归并)原理动画及Python、Java实现
  • 进程、线程的区别
  • identYwaf:一款基于盲推理识别技术的WAF检测工具
  • LLM - GPT(Decoder Only) 类模型的 KV Cache 公式与原理 教程
  • 解决:pip install flash-attn安装失败案例【cuda】【torch】【flash-attn】
  • mysql 不同版本安装不同端口
  • 企业级Mysql 集群技术部署
  • 55.基于IIC协议的EEPROM驱动控制(2)
  • 使用Spring Cloud Consul进行分布式配置的深度解析与实战
  • 【中学教资-信息技术】多媒体文件大小的存储
  • 【计组 | Cache原理】讲透Cache的所有概念与题型方法
  • BMC lighttpd kvm数据分析(websocket)
  • 2018天猫双11|这就是阿里云!不止有新技术,更有温暖的社会力量
  • C++回声服务器_9-epoll边缘触发模式版本服务器
  • magento2项目上线注意事项
  • REST架构的思考
  • WinRAR存在严重的安全漏洞影响5亿用户
  • 漂亮刷新控件-iOS
  • 前端技术周刊 2018-12-10:前端自动化测试
  • 使用 Xcode 的 Target 区分开发和生产环境
  • 使用阿里云发布分布式网站,开发时候应该注意什么?
  • 首页查询功能的一次实现过程
  • 小程序01:wepy框架整合iview webapp UI
  • 小程序上传图片到七牛云(支持多张上传,预览,删除)
  • 一份游戏开发学习路线
  • kubernetes资源对象--ingress
  • 专访Pony.ai 楼天城:自动驾驶已经走过了“从0到1”,“规模”是行业的分水岭| 自动驾驶这十年 ...
  • ​【已解决】npm install​卡主不动的情况
  • # 数论-逆元
  • #define用法
  • #传输# #传输数据判断#
  • #单片机(TB6600驱动42步进电机)
  • $.each()与$(selector).each()
  • ${factoryList }后面有空格不影响
  • (~_~)
  • (2)Java 简介
  • (3)Dubbo启动时qos-server can not bind localhost22222错误解决
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息
  • (el-Date-Picker)操作(不使用 ts):Element-plus 中 DatePicker 组件的使用及输出想要日期格式需求的解决过程
  • (HAL)STM32F103C6T8——软件模拟I2C驱动0.96寸OLED屏幕
  • (第8天)保姆级 PL/SQL Developer 安装与配置
  • (蓝桥杯每日一题)平方末尾及补充(常用的字符串函数功能)
  • (论文阅读31/100)Stacked hourglass networks for human pose estimation
  • (论文阅读40-45)图像描述1
  • (自适应手机端)响应式新闻博客知识类pbootcms网站模板 自媒体运营博客网站源码下载
  • *setTimeout实现text输入在用户停顿时才调用事件!*
  • .gitignore文件—git忽略文件
  • .NET 4.0网络开发入门之旅-- 我在“网” 中央(下)
  • .NET CF命令行调试器MDbg入门(四) Attaching to Processes
  • .NET 将多个程序集合并成单一程序集的 4+3 种方法
  • .NET 快速重构概要1
  • .NET 中使用 TaskCompletionSource 作为线程同步互斥或异步操作的事件