当前位置:网站首页>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行:输出验证结果.
边栏推荐
猜你喜欢
随机推荐
Mysql高级篇学习总结13:多表连接查询语句优化方法(带join语句)
shell变量
从零开始Blazor Server(7)--使用Furion权限验证
Mysql——》类型转换符binary
Xilinx VIVADO 中 DDR3(Naive)的使用(2)读写设计
RL78 development environment
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
Win11怎么重装显卡驱动程序?Win11显卡驱动怎么卸载重装?
数据库对象
DDL和DML的补充
什么是 DevOps?看这一篇就够了!
POJ3687Labeling Balls题解
Zhihu Data Analysis Training Camp
MySql数据库入门的基本操作
云原生Devops 的实现方法
The use of DDR3 (Naive) in Xilinx VIVADO (2) Read and write design
bitset的基本用法
Leetcode brush questions - 543. Diameter of binary trees, 617. Merging binary trees (recursive solution)
Leetcode刷题——543. 二叉树的直径、617. 合并二叉树(递归解决)
学会使用set和map的基本接口









