c++11 的 list deque 和 vector 增加了emplace_back函數,相對於push_back函數,它減少了一次類的構造,因此效率更高,推薦使用。
#include <list> #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(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) = default; }; int main() { std::list<President> elections; std::cout << "emplace_back:\n"; elections.emplace_back("Nelson Mandela", "South Africa", 1994); std::list<President> reElections; std::cout << "\npush_back:\n"; reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); }
輸出:
emplace_back:
I am being constructed.
push_back:
I am being constructed.
I am being moved.
我們看到,emplace_back通過使用“可變長模板”減少了一次構造函數的執行。
和 push_back 一樣,emplace_back 可能會導致 vector, deque 迭代器失效,具體就是:
1. 如果vector size() 大於 capacity() ,empace_back之后,所有的迭代器和引用失效; 否則,僅僅 end() 失效
2. deque 所有迭代器失效,沒有引用失效