emplace_back() 和 push_back 的区别(转)
在引入右值引用,转移构造函数,转移复制运算符之前,通常使用push_back()向容器中加入一个右值元素(临时对象)的时候,首先会调用构造函数构造这个临时对象,然后需要调用拷贝构造函数将这个临时对象放入容器中。原来的临时变量释放。这样造成的问题是临时变量申请的资源就浪费。
引入了右值引用,转移构造函数(请看这里)后,push_back()右值时就会调用构造函数和转移构造函数。
在这上面有进一步优化的空间就是使用emplace_back
emplace_back
函数原型:
1 template <class... Args> 2 void emplace_back (Args&&... args);
在容器尾部添加一个元素,这个元素原地构造,不需要触发拷贝构造和转移构造。而且调用形式更加简洁,直接根据参数初始化临时对象的成员。
给出一个示例,这个示例很有用。
1 #include <vector> 2 #include <string> 3 #include <iostream> 4 5 struct President 6 { 7 std::string name; 8 std::string country; 9 int year; 10 11 President(std::string p_name, std::string p_country, int p_year) 12 : name(std::move(p_name)), country(std::move(p_country)), year(p_year) 13 { 14 std::cout << "I am being constructed.\n"; 15 } 16 President(const President& other) 17 : name(std::move(other.name)), country(std::move(other.country)), year(other.year) 18 { 19 std::cout << "I am being copy constructed.\n"; 20 } 21 President(President&& other) 22 : name(std::move(other.name)), country(std::move(other.country)), year(other.year) 23 { 24 std::cout << "I am being moved.\n"; 25 } 26 President& operator=(const President& other); 27 }; 28 29 int main() 30 { 31 std::vector<President> elections; 32 std::cout << "emplace_back:\n"; 33 elections.emplace_back("Nelson Mandela", "South Africa", 1994); //没有类的创建 34 35 std::vector<President> reElections; 36 std::cout << "\npush_back:\n"; 37 reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); 38 39 std::cout << "\nContents:\n"; 40 for (President const& president: elections) { 41 std::cout << president.name << " was elected president of " 42 << president.country << " in " << president.year << ".\n"; 43 } 44 for (President const& president: reElections) { 45 std::cout << president.name << " was re-elected president of " 46 << president.country << " in " << president.year << ".\n"; 47 } 48 49 }
输出
1 emplace_back: 2 I am being constructed. 3 4 push_back: 5 I am being constructed. 6 I am being moved. 7 8 Contents: 9 Nelson Mandela was elected president of South Africa in 1994.
转自:https://blog.csdn.net/xiaolewennofollow/article/details/52559364
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
分类:
STL
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了