当前位置:网站首页>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行:输出验证结果.
边栏推荐
- 【LeetCode】700.二叉搜索树
- 数据库对象
- 不会还有人不知道防抖吧?
- linux下数据库初始化密码
- ESP8266-Arduino编程实例-MQ3酒精传感器驱动
- IBM Q复制新增QSUB
- 热成像测温的原理是什么呢?你知道吗?
- DDL和DML的补充
- Leetcode brush questions - binary search tree related topics (98. Verify binary search tree, 235. The nearest common ancestor of binary search tree, 1038. From binary search tree to bigger sum tree, 5
- 蒲丰投针学习笔记
猜你喜欢

Zikko上市同时搭载HDMI2.1和2.5GbE新款雷电4扩展坞

Leetcode brush - structure binary tree (105. Once upon a time sequence and the sequence structure binary tree traversal sequence, 106. From the sequence with the sequence structure binary tree travers

Oracle中对临时表空间执行shrink操作

Xilinx VIVADO 中 DDR3(Naive)的使用(1)创建 IP 核

Zikko launches new Thunderbolt 4 docking station with both HDMI2.1 and 2.5GbE

Leetcode Brush Questions - Path Sum

Mysql高级篇学习总结13:多表连接查询语句优化方法(带join语句)

【LeetCode】653. 两数之和 IV - 输入 BST

化繁为简!阿里新产亿级流量系统设计核心原理高级笔记(终极版)

The use of DDR3 (Naive) in Xilinx VIVADO (3) simulation test
随机推荐
多行函数;group_by分组;having分组后筛选;单表查询总结
将博客搬至CSDN
Doing Homework HDU - 1074
Rust 从入门到精通04-变量
Xilinx VIVADO 中 DDR3(Naive)的使用(2)读写设计
手搓一个“七夕限定”,用3D Engine 5分钟实现烟花绽放效果
Mysql高级篇学习总结13:多表连接查询语句优化方法(带join语句)
Four ways to traverse a Map
使用.NET简单实现一个Redis的高性能克隆版(二)
map的一道题目<单词识别>
秒云成功入选《2022爱分析 · 银行数字化厂商全景报告》,智能运维能力获认可
深度强化学习与APS的一些感想
bitset的基本用法
Mysql数据类型
The use of DDR3 (Naive) in Xilinx VIVADO (3) simulation test
多表查询
MySQL 45 讲 | 10 MySQL为什么有时候会选错索引?
ESP8266-Arduino编程实例-MQ3酒精传感器驱动
Disc burning steps
怎么禁止textarea拉伸