c++11新特性之cmplace(变参模板和完美转发)

优点:

c++11的新特性变参模板和完美转发相对原有的方式能够提升代码的执行效率.

概述:

变参模板使得cmplace可以接受任意参数,这样就可以适用于任意对象的构建
完美转发使得接收下来的参数,能够原样的传递给对象的构造函数,这带来另一种方便性

代码参考:

#include <iostream>
#include <vector>
#include <deque>
#include <list>

using namespace std;

//树
class tree {
public:
	tree() {
		cout << "无参构造函数被调用!" << endl;
	}
	tree(int altitude, const char* name) {
		this->altitude = altitude;
		strcpy_s(this->name, 64, name);
		cout << "调用有参构造函数!" << endl;
		cout << "树名:" << name << "   树高:" << altitude << endl;
	}

	tree(const tree& s) {
		this->altitude = s.altitude;
		strcpy_s(this->name, 64, s.name);
		cout << "调用拷贝构造函数!" << endl;
	}

	~tree() {
		cout << "调用析构构造函数!" << endl;
	}

private:
	int altitude; //树的高度
	char name[64]; //树的种类
};

int main() {
	deque<tree> deqStu;

	//先定义,再插入
	tree locustTree(18, "槐树"); //将调用有参构造函数
	deqStu.push_back(locustTree); //将调用拷贝构造函数

	//直接插入临时对象
	deqStu.push_back(tree(25, "杉树")); //将调用有参,拷贝和析构函数

	//c++11新特性 变参模板和完美转发
	deqStu.emplace_back(20, "杨树"); //只调用有参函数
	deqStu.emplace(deqStu.begin(), 16, "橡树"); //只调用有参函数

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值