c++ - 向 vector 中插入数据时多次调用复制构造函数

标签 c++

#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]);
    }

}

当数据插入 vector 时,使用复制构造函数将该数据复制到 vector。

当我运行这个程序时,

  1. 对于第一次插入(i=0),调用一次复制构造函数。
  2. 第二次插入(i=1),调用两次拷贝构造函数
  3. 第三次插入(i=3),调用三次拷贝构造函数
  4. 对于第四次插入(i=3),调用了四次拷贝构造函数
  5. 第五次插入(i=4),调用五次拷贝构造函数

谁能告诉我为什么会这样?对于每次插入,复制构造函数不应该只被调用一次吗?

最佳答案

调用 push_back() 会根据需要增加 vector 的大小,这涉及复制 vector 的内容。因为您已经知道它将包含五个元素,可以在循环之前使用 v.reserve(5);,或者使用范围构造函数:

base obase[5]={4,14,19,24,29};
vector<base> v(obase, obase+5);

关于c++ - 向 vector 中插入数据时多次调用复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46880612/

相关文章:

c++ - 将字符串转换为 double ,而字符串有 N 位小数,C++

c++ - 模拟管理员用户时使用 AddIPAddress 时出现问题

c++ - 函数类型T是什么意思?

c++ - C++对象数组中的奇怪数字

c++ - 错误 'TempSLLNODE' : use of class template requires template argument list

c++ - Windows C++ 如何安装 GLFW 库?

c++ - 无法在 Ubuntu 中编译简单的 C++ 程序

c++ - std::packaged_task 没有违反销毁 promise ?

c++ - 使用带有参数 cin.get() 或 .getline() 的函数调用

c++ - 通过引用或按值将共享指针作为参数传递给类