Monday, November 1, 2021

[C++] push_back VS emplace_back


remember to use reserve :) 

https://www.geeksforgeeks.org/push_back-vs-emplace_back-in-cpp-stl-vectors/

emplace_back() 和 push_back() 的区别,就在于底层实现的机制不同。push_back() 向容器尾部添加元素时,首先会创建这个元素,然后再将这个元素拷贝或者移动到容器中(如果是拷贝的话,事后会自行销毁先前创建的这个元素);而 emplace_back() 在实现时,则是直接在容器尾部创建这个元素,省去了拷贝或移动元素的过程。


为了让大家清楚的了解它们之间的区别,我们创建一个包含类对象的 vector 容器,如下所示:
  1. #include <vector>
  2. #include <iostream>
  3. using namespace std;
  4. class testDemo
  5. {
  6. public:
  7. testDemo(int num):num(num){
  8. std::cout << "调用构造函数" << endl;
  9. }
  10. testDemo(const testDemo& other) :num(other.num) {
  11. std::cout << "调用拷贝构造函数" << endl;
  12. }
  13. testDemo(testDemo&& other) :num(other.num) {
  14. std::cout << "调用移动构造函数" << endl;
  15. }
  16. private:
  17. int num;
  18. };
  19. int main()
  20. {
  21. cout << "emplace_back:" << endl;
  22. std::vector<testDemo> demo1;
  23. demo1.emplace_back(2);
  24. cout << "push_back:" << endl;
  25. std::vector<testDemo> demo2;
  26. demo2.push_back(2);
  27. }
运行结果为:

emplace_back:
调用构造函数
push_back:
调用构造函数
调用移动构造函数

在此基础上,读者可尝试将 testDemo 类中的移动构造函数注释掉,再运行程序会发现,运行结果变为:

emplace_back:
调用构造函数
push_back:
调用构造函数
调用拷贝构造函数

由此可以看出,push_back() 在底层实现时,会优先选择调用移动构造函数,如果没有才会调用拷贝构造函数。

显然完成同样的操作,push_back() 的底层实现过程比 emplace_back() 更繁琐,换句话说,emplace_back() 的执行效率比 push_back() 高。因此,在实际使用时,建议大家优先选用 emplace_back()。

由于 emplace_back() 是 C++ 11 标准新增加的,如果程序要兼顾之前的版本,还是应该使用 push_back()。


La fonction void emplace_back(Type&& _Val)fournie par MSCV10 est non conforme et redondante, car comme vous l'avez noté, elle est strictement équivalente à push_back(Type&& _Val).

Mais la vraie forme C ++ 0x de emplace_backest vraiment utile void emplace_back(Args&&...):; 



 

No comments:

Post a Comment