2014-04-12 102 views
1

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)?另外,为什么“Matilda”在vect2中被称为两次?

+0

你所说的“实际对象”呢? – ooga

+0

至于额外的“Matilda”,我建议你检查你的代码中没有多余的一个,重新编译并重新运行。 – ooga

+0

@ooga在代码中,只有两个对象都推到“vect2” – Manuel

回答

1

即使在载体的push_back方法接收一个参考,它需要,如果不复制通过参数传递的价值,认为在这种情况下,会发生什么事时,局部变量“明德”超出范围之前“ 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 ::矢量需要增加它的内部阵列的大小,将所述元件从一个阵列复制到其它,然后再次调用复制构造。这就是为什么玛蒂尔达第二次被复制。 (尝试评论vect2.push_back(timmy);这一行,看看Matilda是如何复制一次的)。

+4

*“每次需要将其中一个元素从一个位置移动到其内部'数组'内*” - 这不会发生。当由于容量不足而发生重新分配时,它将从一个内部阵列复制到新阵列。 –

+0

谢谢,你是对的,我会更新我的答案。 – MondKin

+0

Thankssssssssss – Manuel

相关问题