浅拷贝和深拷贝

F:\C++\visual studio 2015\Projects\拷贝构造函数合集

浅拷贝:
浅拷贝中根本就没有定义拷贝构造函数.//自己写的birthDate为非指针
Person::Person(int id, int year, int month, int day)
{
    this->id = id;
    Date birthDateNew(year, month, day);//直接初始化,nice
    this->birthDate = birthDateNew; //注意这里的this->birthDate属于成员函数,会存活到对象撤销前。
}
//指针类型的birthDate
Person::Person(int id, int year, int month, int day)
{
  id_ = id;
  birthDate = new Date(year, month, day);//在堆上
}

深拷贝:

Person::Person(Person &person)
{
 id = person.id;
 Date *p = person.getBirthDate();
 birthDate = new Date(*p); //解引用,把p指向的内容给birthDate复制了一份.调用了Date的拷贝构造函数,作用就是复制*p的内容.
                     //因为*p里全是非指针成员变量,所以不定义Date的拷贝构造函数,利用默认的也能成功完成复制.
                     //但person因为有指针成员函数,所以要自定义拷贝构造函数.    new出来的,所以在堆区.
                           // 之所以能够深拷贝, 是因为有自定义的拷贝构造函数, 以及有显式的new语句
 std::cout << "*birthDate的内容" << (*birthDate).getYear() << std::endl;
}


为什么要深拷贝:类中存在指针数据成员时,系统默认的拷贝只是简单的拷贝指针,属于浅拷贝,不安全.

 

posted @ 2019-08-18 21:20  心媛意码  阅读(142)  评论(0编辑  收藏  举报