1. 值参传递所进行的赋值称为浅拷贝赋值,浅拷贝赋值导致形参和实参的指针成员指向共同的存储单元。由此造成的后果是一旦被调用的函数返回,形参析构就必然会释放其指针所指向的存储单元,该存储单元可能会立刻被操作系统分配给其他程序,但本程序并不知道该存储单元被分配给其他存储单元,必然造成一个程序非法访问另一个内存单元;
#include <iostream>
using namespace std;
class ARRAY{
int size;
int *p;
public:
int get(int x);
ARRAY(int s);
~ARRAY();
};
int ARRAY::get(int x)
{
return p[x];
}
ARRAY::ARRAY(int s)
{
int i;
p = new int[size = s];
for(int i=0;i<s;i++)
p[i] = 1;
cout << "Construct Array (" << s << ")" << endl;
}
ARRAY::~ARRAY()
{
int i;
if(p){
delete p;
p = 0;
}
cout << "Deconstuct array (" <<size << ")" <<endl;
}
void func(ARRAY y)
{
cout << "func: ";
}
int main()
{
cout << "main:";
ARRAY a(6);
cout << "main: a[0] = " << a.get(0) << endl;
func(a);
int *q = new int[6];
q[0] = 8;
cout << "main : a[0] = " << a.get(0) << endl;
system("pause");
return 0;
}
输出
main:Construct Array (6)
main: a[0] = 1
func: Deconstuct array (6)
main : a[0] = 8
2. 在非引用类型的形参对象包含指针数据成员时,必须进行深拷贝才能避免内存保护错误,即必须传递参数前为形参对象的指针分配新的存储单元,而后将实参对象的指针成员随之向的存储单元的内容复制到新的存储单元中;为了在传递参数时进行深度拷贝,必须将析构函数的参数类型定义为类或者类的引用;
#include <iostream>
using namespace std;
class ARRAY
{
int size;
int *p;
public:
int get(int x);
ARRAY(int s);
ARRAY(ARRAY &r);
~ARRAY();
};
int ARRAY::get(int x)
{
return p[x];
}
ARRAY::ARRAY(int s)
{
int i;
p = new int[size = s];
for (int i = 0; i < s; i++)
p[i] = 1;
cout << "Construct Array (" << s << ")" << endl;
}
ARRAY::ARRAY(ARRAY &r)
{
int i;
p = new int[size = r.size];
for (int i = 0; i < r.size; i++)
p[i] = r.p[i];
cout << "Construct Array (" << size << ")" << endl;
}
ARRAY::~ARRAY()
{
int i;
if (p)
{
delete p;
p = 0;
}
cout << "Deconstuct array (" << size << ")" << endl;
}
void func(ARRAY y)
{
cout << "func: ";
}
int main()
{
cout << "main:";
ARRAY a(6);
cout << "main: a[0] = " << a.get(0) << endl;
func(a);
int *q = new int[6];
q[0] = 8;
cout << "main : a[0] = " << a.get(0) << endl;
system("pause");
return 0;
}
输出
main:Construct Array (6)
main: a[0] = 1
Construct Array (6)
func: Deconstuct array (6)
main : a[0] = 1