std :: vector和copy构造函数 [英] std::vector and copy constructors

查看:176
本文介绍了std :: vector和copy构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

vector<X> v;
X x;
v.push_back(x); v.push_back(x); v.push_back(x);

为什么这个代码调用类的复制构造函数 X 6次? (使用g ++ 4.7.2 STL)

Why this code calls the copy constructor of a class X 6 times? (using g++ 4.7.2 STL)

请让我知道正确这个STL发生了什么。 / p>

Please, I'd like to know it precisely what happens under hood with this particular STL.

推荐答案

当您插入 x push_back ),内存被重新分配,最终为新元素腾出空间。已插入的成员必须使用复制构造函数 X(const X&)复制。

When you insert x with push_back(), the memory is reallocated eventually to make room for the new element. The already inserted members must then be copied around using the copy constructor X(const X&).

插入

v.reserve(3);


$ b < c $ c> s,因此,只有三个调用 X(const X&)

这篇关于std :: vector和copy构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆