在引入右值引用,转移构造函数,转移复制运算符之前,通常使用push_back()向容器中加入一个右值元素(临时对象)的时候,首先会调用构造函数构造这个临时对象,然后需要调用拷贝构造函数将这个临时对象放入容器中。原来的临时变量释放。这样造成的问题是临时变量申请的资源就浪费。
引入了右值引用,转移构造函数(请看这里)后,push_back()右值时就会调用构造函数和转移构造函数。
在这上面有进一步优化的空间就是使用emplace_back
emplace_back
函数原型:
1 template <class... Args> 2 void emplace_back (Args&&... args);
在容器尾部添加一个元素,这个元素原地构造,不需要触发拷贝构造和转移构造。而且调用形式更加简洁,直接根据参数初始化临时对象的成员。
给出一个示例,这个示例很有用。
1 #include <vector> 2 #include <string> 3 #include <iostream> 4 5 struct President 6 { 7 std::string name; 8 std::string country; 9 int year; 10 11 President(std::string p_name, std::string p_country, int p_year) 12 : name(std::move(p_name)), country(std::move(p_country)), year(p_year) 13 { 14 std::cout << "I am being constructed. "; 15 } 16 President(const President& other) 17 : name(std::move(other.name)), country(std::move(other.country)), year(other.year) 18 { 19 std::cout << "I am being copy constructed. "; 20 } 21 President(President&& other) 22 : name(std::move(other.name)), country(std::move(other.country)), year(other.year) 23 { 24 std::cout << "I am being moved. "; 25 } 26 President& operator=(const President& other); 27 }; 28 29 int main() 30 { 31 std::vector<President> elections; 32 std::cout << "emplace_back: "; 33 elections.emplace_back("Nelson Mandela", "South Africa", 1994); //没有类的创建 34 35 std::vector<President> reElections; 36 std::cout << " push_back: "; 37 reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); 38 39 std::cout << " Contents: "; 40 for (President const& president: elections) { 41 std::cout << president.name << " was elected president of " 42 << president.country << " in " << president.year << ". "; 43 } 44 for (President const& president: reElections) { 45 std::cout << president.name << " was re-elected president of " 46 << president.country << " in " << president.year << ". "; 47 } 48 49 }
输出
1 emplace_back: 2 I am being constructed. 3 4 push_back: 5 I am being constructed. 6 I am being moved. 7 8 Contents: 9 Nelson Mandela was elected president of South Africa in 1994.
转自:https://blog.csdn.net/xiaolewennofollow/article/details/52559364