拷贝构造函数 浅拷贝遇到的问题 如何用深拷贝解决

    科技2022-09-01  104

    使用条件: 1.明确表示由一个对象初始化另一个对象

    2当对象作为函数的实参传递给形参时

    3当对象作为函数的返回值时

    #include <iostream> using namespace std; class Person{ private: int m_age; public: Person(int age):m_age(age){ cout<<"Constructor; age = "<<this->m_age<<endl; } Person(const Person &p){ this->m_age = p.m_age; cout<<"Copy Construct; age = "<<this->m_age<<endl;} }; int main(){ Person p1(10); Person p2(p1); Person pEqualNum = 3; }

    输出:

    Constructor; age = 10 Copy Construct; age = 10 Constructor; age = 3

    深浅拷贝

    拷贝者和被拷贝者若是同一个地址,则为浅拷贝,反之为深拷贝。

    浅拷贝以及出现的问题:

    #include <iostream> using namespace std; class person{ private: int *m_age; public: person(int *age):m_age(age){ cout<<"普通构造 age="<<*(this->m_age)<<endl; } person(const person &p){ this->m_age = p.m_age; cout<<"拷贝构造 age="<<*(this->m_age)<<endl; } ~person(){ delete m_age; cout<<"~person 析构完成!"<<endl; } }; int main(){ int *a = new int(10); person p1(a); person p2=p1; return 0; }

    输出:

    普通构造 age=10 拷贝构造 age=10 ~person 析构完成! free(): double free detected in tcache 2 [1] 46504 abort (core dumped) ./Deep

    深拷贝以及解决办法

    #include <iostream> using namespace std; class person{ private: int *m_age; public: person(int *age):m_age(age){ cout<<"普通构造 age="<<*(this->m_age)<<endl; } person(const person &p){ int *new_age = new int; //深拷贝+ *new_age = *p.m_age; //深拷贝+ this->m_age = new_age; //深拷贝+ cout<<"拷贝构造 age="<<*(this->m_age)<<endl; } ~person(){ delete m_age; cout<<"~person 析构完成!"<<endl; } }; int main(){ int *a = new int(10); person p1(a); person p2=p1; return 0; }

    输出:

    普通构造 age=10 拷贝构造 age=10 ~person 析构完成! ~person 析构完成!

    没有出现double free!

    Processed: 0.014, SQL: 9