c++ - 为什么这里要调用拷贝构造函数呢?

标签 c++ stdvector

主.cc

#include <iostream>
using namespace std;
#include <vector>
#include "Student.h"


int main()
{
  Student matilda("100567899", "Matilda");
  Student joe("100234555", "Joe");
  Student stanley("100234888", "Stanley");
  Student timmy("100234888", "Timmy");



  vector<Student*> comp2404;

  comp2404.push_back(&matilda);
  comp2404.push_back(&joe);
  comp2404.push_back(&stanley);
  comp2404.push_back(&timmy);

  vector<Student> vect2;
  vect2.push_back(matilda);
  vect2.push_back(timmy);

  cout<<"all done"<<endl;

  return 0;
}

Student.cc

#include <iostream>
using namespace std;
#include <string>

#include "Student.h"


Student::Student(string nu, string na)
    : number(nu), name(na)
{ 
  cout<<"-- Student default ctor "<<name<<endl;
}

Student::Student(const Student& stu)
{
  name   = stu.name;
  number = stu.number;
  cout<<"-- Student copy ctor "<<name<<endl;
}

Student::~Student()
{ 
  cout<<"-- Student dtor"<<endl;
}

string Student::getName() const { return name; }

void Student::setName(string n) { name = n; }

ostream& operator<<(ostream& output, Student& stu)
{
  output<<"Student:  "<<stu.number<<"  "<<stu.name<<endl;
  return output;
}

输出是:

-- Student default ctor Matilda
-- Student default ctor Joe
-- Student default ctor Stanley
-- Student default ctor Timmy

-- Student copy ctor Matilda
-- Student copy ctor Timmy
-- Student copy ctor Matilda
-- Student dtor
all done
-- Student dtor
-- Student dtor
-- Student dtor
-- Student dtor
-- Student dtor
-- Student dtor

为什么vect2会调用拷贝构造函数? vector 不能只存储实际对象(Matilda 和 Timmy)吗?另外,为什么在 vect2 中两次调用“Matilda”?

最佳答案

即使vector中的push_back方法接收到一个引用,它也需要复制参数传递的值,如果不是,想想在这种情况下会发生什么,当局部变量'matilda'在'v'之前超出范围' 被访问:

int main()
{
    std:vector<Student> v;
    {
         Student matilda("100567899", "Matilda");
         v.push_back(matilda);
    }
    // Try to access the first element of 'v' here:
    std::cout << v[0].getName() << std::endl;
}

这就是它调用复制构造函数的原因。

现在,每次 std::vector 需要增加其内部数组的大小时,它会将元素从一个数组复制到另一个数组,然后再次调用复制构造函数。这就是第二次复制玛蒂尔达的原因。 (尝试注释 vect2.push_back(timmy); 行,看看 Matilda 是如何只被复制一次的)。

关于c++ - 为什么这里要调用拷贝构造函数呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23025465/

相关文章:

C++03 : Add fields to several derived classes

c++ - 如何在C++中将输入正确读取为2D vector vector <vector <int >>

c++ - vector Push_Back VS Emplace_Back

c++ - 在 Visual Studio 2019 C++ 中,如何扩展动态分配的数组以显示其所有元素?

c++ - 四元数到旋转矩阵,使用特征库的值不正确

c++ - 带有空捕获的 Lambda 表达式

c++ - 由于编译器读取代码的方式而导致输入变量的问题

c++ - 如何将数组的内容插入 vector 中?

c++ - vector::resize 增加多少容量?

c++ - std::optional<std::reference_wrapper<T>> - 可以吗?