此功能是为了提高往容器里存储对象效率而产生的。
变参模板 - 使得 emplace 可以接受任意参数,这样就可以适用于任意对象的构建
完美转发 - 使得接收下来的参数 能够原样的传递给对象的构造函数,从而减少多余的操作,提高效率
传统的:
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
class student {
public:
student() {
cout << "无参构造函数被调用!" << endl;
}
student(int age, string name) {
this->age = age;
this->name = name;
cout << "有参构造函数被调用!" << endl;
cout << "姓名: " << name << " 年龄:" << age << endl;
}
student(const student& s) {
this->age = s.age;
this->name = s.name;
cout << "拷贝构造函数" << endl;
}
~student() {
cout << "析构函数被调用!" << endl;
}
private:
int age;
string name;
};
int main() {
vector<student> stus;
student s1(18,"小花");
stus.push_back(s1);
system("pause");
return 0;
}
新版
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
class student {
public:
student() {
cout << "无参构造函数被调用!" << endl;
}
student(int age, string name) {
this->age = age;
this->name = name;
cout << "有参构造函数被调用!" << endl;
cout << "姓名: " << name << " 年龄:" << age << endl;
}
student(const student& s) {
this->age = s.age;
this->name = s.name;
cout << "拷贝构造函数" << endl;
}
~student() {
cout << "析构函数被调用!" << endl;
}
private:
int age;
string name;
};
int main() {
vector<student> stus;
stus.emplace_back(19,"xiaocao");
//stus.emplace(stus.end(),19, "xiaoyao");
//新特性的两种用法,第一种类似于push_back()
//第二种类似于insert()
system("pause");
return 0;
}
从两个程序就可以看出,使用新的版本会使程序效率提高,仅仅使用一次构造函数。