变参模板 - 使得 emplace 可以接受任意参数,这样就可以适用于任意对象的构建。
完美转发 - 使得接收下来的参数 能够原样的传递给对象的构造函数,这带来另一个方便性。
对象放入容器中,会调用拷贝函数。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class student {
public:
student(int age, string name) {
this->age = age;
this->name = name;
cout << "有参构造函数被调用!" << endl;
cout << "姓名:" << name.c_str() << " 年龄:" << age << endl;
}
student(const student &s) {
this->age = s.age;
this->name = s.name;
cout << "拷贝构造函数被调用!" << endl;
}
~student() {
cout << "析构函数被调用" << endl;
}
public:
int age;
string name;
};
int main(void) {
vector<student> vectStu;
vectStu.push_back(student(19, "王大锤"));
system("pause");
return 0;
}
运行结果
当使用方法三时,减少一层拷贝,运行结果。