本文主要是介绍变参模板、完美转发和emplace,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 1 变参模板、完美转发和emplace
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_backcout << "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/C++从入门到精通-高级程序员之路【奇牛学院】
这篇关于变参模板、完美转发和emplace的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!