通过复制构造函数,复制的对象与原对象共享内存么,求各位给个解释
很多时候在我们都不知道拷贝构造函数的情况下,传递对象给函数参数或者函数返回对象都能很好的进行,这是因为编译器会给我们自动产生一个拷贝构造函数,这就是“默认拷贝构造函数”,这个构造函数很简单,仅仅使用“老对象”的数据成员的值对“新对象”的数据成员一一进行赋值
一般分成浅拷贝和深拷贝:
浅拷贝,指的是在对象复制时,只对对象中的数据成员进行简单的赋值,默认拷贝构造函数执行的也是浅拷贝。大多情况下“浅拷贝”已经能很好地工作了,但是一旦对象存在了动态成员,这两个指针会指向堆里的同一个空间
在“深拷贝”的情况下,对于对象中动态成员,就不能仅仅简单地赋值了,而应该重新动态分配空间
#include "stdafx.h"
#include
#include
using namespace std;
class Pstu;
class student
{
public:
friend class Pstu;
student(int aid, char* pstr) :id(aid), name(pstr)
{
cout << "student构造函数被调用" << endl;
count = 0;
}
~student()
{
cout << "student is destructing..." << endl;
}
void display()
{
cout << "id:" << id << endl;
cout << "name:" << name << endl;
}
private:
unsigned int count;
int id;
char* name;
};
//////////////////////////////////////////////////////////
class Pstu
{
public:
Pstu(student* p) :pointer(p)
{
cout << "Pstu" << endl;
(*pointer).count++;
cout << "此时count为:" << (*pointer).count << endl;
}
Pstu(const Pstu& p)
{
pointer = p.pointer;
cout << "此时count为:" << (*pointer).count << endl;
(*pointer).count++;
cout << "Pstu1" << endl;
cout << "此时count为:" << (*pointer).count << endl;
}
~Pstu()
{
(*pointer).count--;
cout << "此时count为:" << (*pointer).count << endl;
if (!(*pointer).count)
{
cout << "Pstu is destructing..." << endl;
delete pointer;
}
//delete pointer;
}
unsigned int get_count()
{
return (*pointer).count;
}
//student& operator* (){ return *pointer; }
//student* operator->(){ return pointer; }
private:
student* pointer;
};
/////////////////////////////////////////////////////////
int main()
{
Pstu p = (new student(1000, "张思源"));
Pstu p1 = p, p2 = p;
cout << p.get_count() << endl;
cout << p1.get_count() << endl;
cout << p2.get_count() << endl;
//p->display();
return 0;
}
既然是通过复制构造函数得到的p1,p2,为什么三个对象中的count 值都是3?
因为你的Pstu(const Pstu& p)这个拷贝函数里有这么一句pointer = p.pointer;
这就使得无论是p1还是p2他们的private成员变量pointer都指向了和p一样的内存地址
所以不管是哪个对象对自己的pointer所指向的对象的count执行++操作,三个对象都能看到
复制应该是指数据值的拷贝