emplace_back和push_back区别,以及vector内存变化

参考链接

void* operator new(size_t size)//重载operator new
{
 	cout << "vector size to: " << size/sizeof(int) << endl;
	 return malloc(size);
}
class test {
public:
 	test() :num(0) { cout << "default construct of " <<0<< endl; };
 	test(int a) :num(a) { cout << "assign construct of " <<a<<endl; };
 	test(test&& t) :num(t.num) { cout << "move construct of " << t.num<< 	endl; };
 	test(const test& t) :num(t.num) { cout << "copy construct of " << t.num<< endl; };//参数前必须加const否则会报错
 //如果不定义,会调用默认的拷贝构造 copy bitwise
 	~test()
 	{
 	 cout << "deconstruct" << endl;
	 };
	private:
 	int num;
};
int main()
{
 	vector<test> a;
 	//https://blog.csdn.net/LiQian06336/article/details/99181398
	 cout << "test" << sizeof(test) << endl;
	 cout << "vector size in memory: " << sizeof(a) << endl;
 	cout << "vector capacity: " << a.capacity() << endl;
 	a.push_back(1);
 	cout << "vector capacity: " << a.capacity() << endl;
 	a.emplace_back(2);
 	/cout << "vector capacity: " << a.capacity() << endl;
 	a.push_back(test(3));
	 cout << "vector capacity: " << a.capacity() << endl;
 	a.emplace_back(test(4));
 	cout << "vector capacity: " << a.capacity() << endl;
}

运行结果,

vector size to: 2
test4
vector size in memory: 16//刚开始会申请内存,用于存放指针,见main函数中的链接
vector capacity: 0//正式开始
assign construct of 1//push_back(1),先构造临时对象
vector size to: 1//再申请内存
move construct of 1//再调用移动构造
deconstruct//销毁临时对象
vector capacity: 1
vector size to: 2//empalce_back,先申请内存,申请的是原来大小的两倍,因为vector要扩容,扩容不是原地扩,而是新找一个更大的地方
assign construct of 2//再在申请得到的新内存上原地构造
copy construct of 1//因为vector的容量由1变为2,需要将原来地方的1拷贝过来
deconstruct//将原地方的1析构
vector capacity: 2
assign construct of 3//同1一样,构造临时对象
vector size to: 3//申请内存,扩容
move construct of 3//将3先移动到新的内存地方上
copy construct of 1//将剩余的移动过来
copy construct of 2
deconstruct//将临时对象3和原来的1和2析构
deconstruct
deconstruct
vector capacity: 3
assign construct of 4
vector size to: 4
move construct of 4//同3
copy construct of 1
copy construct of 2
copy construct of 3
deconstruct
deconstruct
deconstruct
deconstruct
vector capacity: 4
deconstruct
deconstruct
deconstruct
deconstruct

结论:

  • emplace_back和push_back区别在与以参数传入的时候
    ,emplace_back先申请内存,再原地构造,而push_back需要先构造临时对象。
  • 对临时对象的处理上,都依赖与是否存在移动构造,若有,则都优先调用移动构造
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值