当前位置:网站首页>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行:输出验证结果.
边栏推荐
猜你喜欢
随机推荐
请 AI 画家弄了个 logo,网友热议:画得非常好,下次别画了!
【LeetCode】1403.非递增顺序的最小子序列
单调栈一些题目练习
Zhihu Data Analysis Training Camp
Four ways to traverse a Map
DDL和DML的补充
今天15:00 | CVPR 2022 论文分享精彩继续
*W3C* Standards Organization
Oracle中对临时表空间执行shrink操作
Leetcode刷题——路径总和
上帝空间——全球首个基于Web3.0的艺术协议创意平台,拓宽多元艺术融合边界
你知道吗?那些专属于代码的浪漫~
MySQL不提供数组,只能做成表吗?
云原生Devops 的实现方法
什么是 DevOps?看这一篇就够了!
萌宠来袭,如何让“吸猫撸狗”更有保障?
深度强化学习与APS的一些感想
使用函数
浅析深度学习在图像处理中的应用趋势及常见技巧
秒云成功入选《2022爱分析 · 银行数字化厂商全景报告》,智能运维能力获认可









