日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

push_back和emplace_back的区别

發布時間:2024/4/18 编程问答 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 push_back和emplace_back的区别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在引入右值引用,轉移構造函數,轉移復制運算符之前,通常使用push_back()向容器中加入一個右值元素(臨時對象)的時候,首先會調用構造函數構造這個臨時對象,然后需要調用拷貝構造函數將這個臨時對象放入容器中。原來的臨時變量釋放。這樣造成的問題是臨時變量申請的資源就浪費。
引入了右值引用,轉移構造函數后,push_back()右值時就會調用構造函數和轉移構造函數。
在這上面有進一步優化的空間就是使用emplace_back,相較而言,emplace_back整體耗時減少17%。

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.
Franklin Delano Roosevelt was re-elected president of the USA in 1936.

Q:為什么push_back 調用了構造函數之后,調用移動構造函數,而不是調用拷貝構造函數?

A:構造函數生成的對象是一個右值對象,所以使用 push_back(&&) 這個重載函數。

總結

以上是生活随笔為你收集整理的push_back和emplace_back的区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。