文章目录
1 变参模板、完美转发和emplace
变参模板:使得 emplace 可以接受任意参数,这样就可以适用于任意对象的构建。
完美转发 :使得接收下来的参数能够原样的传递给对象的构造函数,这带来另一个方便性,避免构造临时对象,提高效率。
测试代码如下:
#include <iostream>
using namespace std;
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
class student {
public:
student() {
cout << "无参构造函数被调用!" << endl;
}
student(int age, string name, int test) {
this->age = age;
//strncpy_s(this->name, name, 64);
cout << "有参构造函数被调用!" << endl;
cout << "姓名:" << name.c_str() << " 年龄:" << age << endl;
}
student(const student &s) {
this->age = s.age;
//strncpy_s(this->name, s.name, 64);
cout << "拷贝构造函数被调用!" << endl;
}
~student() {
cout << "析构函数被调用" << endl;
}
public:
int age;
string name;
};
int main(void) {
//vector<int> vectInt(10);
deque<int> dqInt;
list<int> lstInt;
vector<student> vectStu(10);
cout << "vectStu size:" << vectStu.size() << endl;
cout << "vectStu capacity:" << vectStu.capacity() << endl;
//插入学生
//方法一 先定义对象,再插入
//student xiaoHua(18, "李校花");
//vectStu.push_back(xiaoHua);
//方法二 直接插入临时对象
//vectStu.push_back(student(19, "王大锤"));
//c++11 新特性: 变参模板和完美转发的表演啦
vectStu.emplace_back(19, "王大锤", 11); //push_back
cout << "vectStu size (1):" << vectStu.size() << endl;
cout << "vectStu capacity(1):" << vectStu.capacity() << endl;
vectStu.emplace(vectStu.end(), 18, "lixiaohua", 12); //相当于 insert.
cout << "vectStu size (2):" << vectStu.size() << endl;
cout << "vectStu capacity (2):" << vectStu.capacity() << endl;
system("pause");
return 0;
}
参考资料:
本文深入探讨了C++中变参模板和完美转发的使用,通过实例展示了如何利用这些特性优化代码,特别是在容器类如vector、deque和list的emplace成员函数中,以避免不必要的对象复制,提升代码效率。
712

被折叠的 条评论
为什么被折叠?



