为什么复制构造函数在这里调用?

时间:2014-04-12 02:42:44

标签: c++ stdvector

Main.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会调用复制构造函数?矢量只能存储实际物体(Matilda和Timmy)吗?另外,为什么&#34; Matilda&#34;在vect2被叫了两次?

1 个答案:

答案 0 :(得分:1)

即使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只被复制一次。)