在向量中插入数据时,多次调用复制构造函数 [英] Copy constructor called many times when data is inserted in vector

查看:80
本文介绍了在向量中插入数据时,多次调用复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream> 
#include< vector>
使用命名空间std;
班级基础
{
int x;
public:
base(int k){x = k; }
void display()
{
cout<< x<< endl;
}

base(const base&)
{
cout<<基础副本构造函数:<< endl;
}
};
int main()
{
vector< base> v;
base obase [5] = {4,14,19,24,29};
for(int i = 0; i< 5; i ++)
{
v.push_back(obase [i]);
}

}

将数据插入向量时,



当我运行此程序时,


  1. 第一次插入(i = 0),调用一次副本构造函数。

  2. 第二次插入(i = 1),两次调用副本构造函数

  3. 用于第三次插入(i = 3),复制三次构造子

  4. 用于第四次插入(i = 3),复制四次副本第五次插入(i = 4)时,构造函数被称为

  5. ,五次复制构造函数被称为

请有人能告诉我为什么会这样吗?对于每次插入,是否不应仅一次调用复制构造函数?

解决方案

如果 v 需要调整其内部缓冲区的大小,它通常会分配一个完全新鲜的内存区域,因此它需要将向量中先前存在的所有对象复制到新位置。



您应该在常规复制中完成复制操作。



您应该在上调用 reserve()向量,如果您可以估计需要多少元素,可以预先预留存储空间。



请注意, std:的调整大小/增长行为:向量与实现有关,因此您的代码示例将在不同的标准库实现下产生不同的结果。


#include <iostream>
#include <vector>
using namespace std;
class base
{
    int x;
public:
    base(int k){x =k; }
    void display()
    {
        cout<<x<<endl;
    }

    base(const base&)
    {
        cout<<"base copy constructor:"<<endl;
    }
};
int main()
{
    vector<base> v;
    base obase[5]={4,14,19,24,29};
    for(int i=0; i<5; i++)
    {
        v.push_back(obase[i]);
    }

}

When data is inserted into vector, copy to that data goes to vector using the copy constructor.

When i run this program,

  1. for the first insertion (i=0), one time copy constructor is called.
  2. for the second insertion (i=1), two times copy constructor is called
  3. for the third insertion (i=3), three times copy constructor is called
  4. for the fourth insertion (i=3), four times copy constructor is called
  5. for the fifth insertion (i=4), five times copy constructor is called

Please any one can tell me why this is happening? For each insertion, shouldn't the copy constructor be called only once?

解决方案

If v needs to resize its internal buffer, it will usually allocate a totally fresh memory area, so it needs to copy all the objects that were previously in the vector to the new location. This is done using regular copying, so the copy constructor is invoked.

You should call reserve() on the vector to reserve storage upfront if you can estimate how many elements you are going to need.

Note that the resize/growth behaviour of std::vector is implementation-dependent, so your code sample will produce different results with different standard library implementations.

这篇关于在向量中插入数据时,多次调用复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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