当前位置:网站首页>Implementation principle of function emplace_back in vector
Implementation principle of function emplace_back in vector
2022-08-04 11:24:00 【Old stubborn and cute】
vector中函数emplace_back的实现原理
在vector中的emplace_back函数, 其效率比push_back高很多!
/*例子中使用的Student类的声明*/
class Student
{
private:
int age;
public:
Student();
explicit Student(int age);
~Student();
int getAge();
};
原理分析
push_back函数
vector<Student> team;
team.push(Student(24));
代码运行过程中, 首先是执行Student()创建了一个临时的Student对象, Then use the copy constructor to copy the value of the member variable of this temporary object toteamin the space.
There are two reasons for the slow efficiency:
- 创建临时Student对象时,需要申请内存空间,Allocating memory space has always been a time-consuming operation
- The copy operation of the copy constructor is also requiredCPU时间的
emplace_back函数
vector<Student> team;
team.emplace_back(24);
- This code achieves the same result as above,都在team里添加了一个24岁的Student对象.
- 但在执行效率上,emplace_back函数很快
其原理就是emplace_backThe function is directly inteamon the existing space,调用了Student类的构造函数,Saves the memory space application for temporary objects and the copy operation of the copy constructor.
emplace_back实现原理
void* ptr = malloc(sizeof(Student));
new (ptr)Student(100);
cout << ((Student*)ptr)->getAge() << endl;
第1行:主要是分配一个Student对象所需的内存空间,但在vector里,这步不需要考虑,内部会在实现;
第2行:这才是重点,通过这样的语法,就可以对已在的内存空间,调用相应的Student类构造函数进行初始化;
第3行:输出验证结果.
边栏推荐
- Win11 file types, how to change?Win11 modify the file suffix
- audio_policy_configuration.xml配置文件详解
- 【黄啊码】MySQL入门—2、使用数据定义语言(DDL)操作数据库
- MySQL 45 讲 | 10 MySQL为什么有时候会选错索引?
- datax oracle to oracle incremental synchronization
- 深度学习------戴口罩和不戴口罩
- 强烈推荐一款优秀且通用的后台管理系统
- datax oracle to oracle增量同步
- [Flight Control Development Advanced Course 7] Crazy Shell Open Source Formation UAV - Formation Flight
- MySQL最大建议行数2000w, 靠谱吗?
猜你喜欢
vscode插件设置——Golang开发环境配置
多行函数;group_by分组;having分组后筛选;单表查询总结
ESP8266-Arduino编程实例-TSL2561亮度传感器驱动
蒲丰投针学习笔记
Win11 file types, how to change?Win11 modify the file suffix
深度学习------pytorch实现划拳模型训练
北京大学,新迎3位副校长!其中一人为中科院院士!
Using .NET to simply implement a high-performance clone of Redis (2)
热成像测温的原理是什么呢?你知道吗?
化繁为简!阿里新产亿级流量系统设计核心原理高级笔记(终极版)
随机推荐
网管交换机与非网管交换机如何选择?
ORA-00054 资源正忙
vector中函数emplace_back的实现原理
*iframe*
深度学习------pytorch实现划拳模型训练
知网网站地址更换
知道创宇EDR系统实力通过中国信通院端点检测与响应产品能力评测
apache dolphin scheduler 文件dolphinscheduler-daemon.sh详解
yolov5——detect.py代码【注释、详解、使用教程】
傅里叶级数与傅里叶变换学习
The use of DDR3 (Naive) in Xilinx VIVADO (1) to create an IP core
浅析深度学习在图像处理中的应用趋势及常见技巧
少即是多:视觉SLAM的点稀疏化(IROS 2022)
将博客搬至CSDN
萌宠来袭,如何让“吸猫撸狗”更有保障?
【黄啊码】MySQL入门—2、使用数据定义语言(DDL)操作数据库
The sword refers to the Great Wall Cannon?Official spy photos of Changan's new pickup
剑指offer专项突击版第19天
化繁为简!阿里新产亿级流量系统设计核心原理高级笔记(终极版)
【虹科案例】基于3D相机组装家具