我遇到了复制构造函数并使用指针作为类的成员变量的想法。讲师告诉我,如果我们使用默认的复制构造函数为具有指针类型成员变量的类创建实例,默认的复制构造函数将使用浅拷贝并导致编译器两次删除相同的内存空间。但是当我尝试使用相同的代码时,我没有发现相同的问题,并且当我从不同的实例输出两个指针的地址时,输出是不同的。我想知道编译器本身是否已将其调整为默认复制构造函数的深度复制,或者代码有问题。谢谢!
#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;
}