Reputation: 23
I came across the idea of a copy constructor and using a pointer as a member variable of the class. The lecturer told me that if we use the default copy constructor to create an instance for a class with a member variable of type pointer, the default copy constructor will use the shallow copy and causing the compiler to delete the same memory space twice. But when I try it I did not find the same issue using the same code, and when I output the address of the two pointers from different instances, the output is different. I wonder if the compiler itself has adapted it to deep copy for the default copy constructer or there is something wrong with the code. Thank you!
#include <iostream>
using namespace std;
class Person
{
public:
Person(int age,int height)
{
m_age = age;
m_height = new int(height);
cout << "Person constructed function with param" << endl;
}
Person(const Person &p)
{
cout << "Person 拷贝构造函数调用" << endl;
m_age = p.m_age;
cout << "here" << endl;
m_height = new int(*p.m_height);
cout << "地址:" << &m_height << endl;
}
Person()
{
cout << "Person constructer function without param" << endl;
}
~Person()
{
if (m_height != NULL)
{
delete m_height;
m_height = NULL;
}
cout << "Person destructer" << endl;
}
int m_age = 0;
int* m_height = NULL;
};
void test01()
{
Person p1(18, 160);
cout << "age of p1: " << p1.m_age <<", height:" << &p1.m_height << endl;
Person p2(p1);
cout << "age of p2: " << p2.m_age << ", height:" << &p2.m_height << endl;
}
int main()
{
test01();
return 0;
}
Upvotes: -1
Views: 410
Reputation: 310980
In your copy constructor, in this statement:
m_age = p.m_age;
You assigned the value of one data member to another.
But in this statement:
m_height = new int(*p.m_height);
You did not assign the value of one data member to another.
If instead, you had written:
m_height = p.m_height;
Then two data members of different objects will point to the same dynamically allocated memory that is freed in the destructor. As a result, two objects will try to free the same memory two times.
This is what the lecturer is warning you about. If you don't write your own copy constructor to deep-copy the dynamic object being pointed at, this shallow-copy of the pointer is the type of code that the default compiler-generated constructor will use.
Upvotes: 2