emplace_back() 和 push_back 的区别
来源:互联网 发布:nginx epoll 编辑:程序博客网 时间:2024/04/25 13:21
在引入右值引用,转移构造函数,转移复制运算符之前,通常使用push_back()向容器中加入一个右值元素(临时对象)的时候,首先会调用构造函数构造这个临时对象,然后需要调用拷贝构造函数将这个临时对象放入容器中。原来的临时变量释放。这样造成的问题是临时变量申请的资源就浪费。
引入了右值引用,转移构造函数(请看这里)后,push_back()右值时就会调用构造函数和转移构造函数。
在这上面有进一步优化的空间就是使用emplace_back
emplace_back
函数原型:
template <class... Args> void emplace_back (Args&&... args);
在容器尾部添加一个元素,这个元素原地构造,不需要触发拷贝构造和转移构造。而且调用形式更加简洁,直接根据参数初始化临时对象的成员。
给出一个示例,这个示例很有用。
#include <vector> #include <string> #include <iostream> struct President { std::string name; std::string country; int year; President(std::string p_name, std::string p_country, int p_year) : name(std::move(p_name)), country(std::move(p_country)), year(p_year) { std::cout << "I am being constructed.\n"; } President(const President& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "I am being copy constructed.\n"; } President(President&& other) : name(std::move(other.name)), country(std::move(other.country)), year(other.year) { std::cout << "I am being moved.\n"; } President& operator=(const President& other); }; int main() { std::vector<President> elections; std::cout << "emplace_back:\n"; elections.emplace_back("Nelson Mandela", "South Africa", 1994); //没有类的创建 std::vector<President> reElections; std::cout << "\npush_back:\n"; reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); std::cout << "\nContents:\n"; for (President const& president: elections) { std::cout << president.name << " was elected president of " << president.country << " in " << president.year << ".\n"; } for (President const& president: reElections) { std::cout << president.name << " was re-elected president of " << president.country << " in " << president.year << ".\n"; }}
输出
emplace_back:I am being constructed.push_back:I am being constructed.I am being moved.Contents:Nelson Mandela was elected president of South Africa in 1994.
0 1
- emplace_back() 和 push_back 的区别
- emplace_back() 和 push_back 的区别
- push_back和emplace_back的区别
- C++ - "emplace_back" 和 "push_back" 的区别
- emplace_back和push_back的区别[转]
- C++11中emplace_back和push_back的区别
- 【C/C++开发】emplace_back() 和 push_back 的区别
- C++容器之emplace_back和push_back
- C++11的push_back, move, rvalue, emplace_back
- Life is short, use emplace_back()。探究一下C++11的push_back, move, rvalue, emplace_back
- C++11使用emplace_back代替push_back
- C++11使用emplace_back代替push_back
- emplace 和 emplace_back
- 论Java的ArrayList.add(e)和C++的vector.push_back(e)的区别
- Vector push_back和迭代器iterator的冲突
- vector和dequeue的push_back比较
- 实战c++中的vector系列--知道emplace_back为何优于push_back吗?
- vector push_back和at
- [ACM湖南省赛] CSU 1806 动态最短路的积分
- UVa 10976 Fraction Again?! 分数拆解 (例题7-3)
- 51单片机 指纹模块 波特率问题解决和命令分析2
- stl remove 和 erase
- cf437C The Child and Toy 贪心
- emplace_back() 和 push_back 的区别
- nginx 403 forbidden错误的解决
- 面试题001
- 415.Valid Palindrome-有效回文串(容易题)
- shell(1)
- STL List deque(待总结)
- maven私库nexus3安装及使用
- java求一维数组的最小值
- C++ "extern c" 关键字(待总结)