生活随笔
收集整理的這篇文章主要介紹了
push_back和emplace_back的区别
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在引入右值引用,轉(zhuǎn)移構(gòu)造函數(shù),轉(zhuǎn)移復(fù)制運(yùn)算符之前,通常使用push_back()向容器中加入一個(gè)右值元素(臨時(shí)對(duì)象)的時(shí)候,首先會(huì)調(diào)用構(gòu)造函數(shù)構(gòu)造這個(gè)臨時(shí)對(duì)象,然后需要調(diào)用拷貝構(gòu)造函數(shù)將這個(gè)臨時(shí)對(duì)象放入容器中。原來(lái)的臨時(shí)變量釋放。這樣造成的問(wèn)題是臨時(shí)變量申請(qǐng)的資源就浪費(fèi)。
引入了右值引用,轉(zhuǎn)移構(gòu)造函數(shù)后,push_back()右值時(shí)就會(huì)調(diào)用構(gòu)造函數(shù)和轉(zhuǎn)移構(gòu)造函數(shù)。
在這上面有進(jìn)一步優(yōu)化的空間就是使用emplace_back,相較而言,emplace_back整體耗時(shí)減少17%。
emplace_back函數(shù)原型:
template <class... Args>
void emplace_back (Args&&... args);
在容器尾部添加一個(gè)元素,這個(gè)元素原地構(gòu)造,不需要觸發(fā)拷貝構(gòu)造和轉(zhuǎn)移構(gòu)造。而且調(diào)用形式更加簡(jiǎn)潔,直接根據(jù)參數(shù)初始化臨時(shí)對(duì)象的成員。
給出一個(gè)示例,這個(gè)示例很有用。
#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); //沒(méi)有類(lèi)的創(chuàng)建 ?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 調(diào)用了構(gòu)造函數(shù)之后,調(diào)用移動(dòng)構(gòu)造函數(shù),而不是調(diào)用拷貝構(gòu)造函數(shù)?
A:構(gòu)造函數(shù)生成的對(duì)象是一個(gè)右值對(duì)象,所以使用 push_back(&&) 這個(gè)重載函數(shù)。
總結(jié)
以上是生活随笔為你收集整理的push_back和emplace_back的区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。