变参模板、完美转发和emplace
生活随笔
收集整理的這篇文章主要介紹了
变参模板、完美转发和emplace
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 1 變參模板、完美轉(zhuǎn)發(fā)和emplace
1 變參模板、完美轉(zhuǎn)發(fā)和emplace
變參模板:使得 emplace 可以接受任意參數(shù),這樣就可以適用于任意對象的構(gòu)建。
完美轉(zhuǎn)發(fā) :使得接收下來的參數(shù)能夠原樣的傳遞給對象的構(gòu)造函數(shù),這帶來另一個方便性,避免構(gòu)造臨時對象,提高效率。
測試代碼如下:
#include <iostream> using namespace std;#include <vector> #include <list> #include <deque> #include <algorithm>class student { public:student() {cout << "無參構(gòu)造函數(shù)被調(diào)用!" << endl;}student(int age, string name, int test) {this->age = age;//strncpy_s(this->name, name, 64);cout << "有參構(gòu)造函數(shù)被調(diào)用!" << endl;cout << "姓名:" << name.c_str() << " 年齡:" << age << endl;}student(const student &s) {this->age = s.age;//strncpy_s(this->name, s.name, 64);cout << "拷貝構(gòu)造函數(shù)被調(diào)用!" << endl;}~student() {cout << "析構(gòu)函數(shù)被調(diào)用" << 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;//插入學(xué)生//方法一 先定義對象,再插入//student xiaoHua(18, "李校花");//vectStu.push_back(xiaoHua);//方法二 直接插入臨時對象//vectStu.push_back(student(19, "王大錘"));//c++11 新特性: 變參模板和完美轉(zhuǎn)發(fā)的表演啦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); //相當(dāng)于 insert.cout << "vectStu size (2):" << vectStu.size() << endl;cout << "vectStu capacity (2):" << vectStu.capacity() << endl;system("pause");return 0; }參考資料:
總結(jié)
以上是生活随笔為你收集整理的变参模板、完美转发和emplace的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 海底捞的成功有哪些因素?火锅是一个良好的
- 下一篇: set和multiset