使用复制构造函数的程序输出错误

Error in output of a program using copy constructor

本文关键字:程序 输出 错误 构造函数 复制      更新时间:2023-10-16

我对刚刚制作的程序有一个非常简单的查询。如果你执行这个基本代码:

#include <iostream>
#include <vector>
class Exam
{
public:
int b;
Example(int a)
{
b = a;
}
Exam(const Exam &other)
{
printf("Copy constructor of %dn", other.b);
b = other.b;
}
};
int main()
{
std::vector<Exam> myvector;
Exam ex1(1);
Exam ex2(2);
myvector.push_back(ex1);
myvector.push_back(ex2);
return 1;
}

它生成以下输出:

Copy constructor of 1
Copy constructor of 2
Copy constructor of 1

为什么"1"的复制构造函数执行两次,而"2"的复制构造函数只执行一次?

尝试添加该行

myvector.reserve(2);

在您声明后立即

std::vector<Example> myvector;

当向量必须调整自身大小以允许push_back第二个示例时,幕后似乎正在发生一些事情。