C++ 引用对象

1. 值参传递所进行的赋值称为浅拷贝赋值,浅拷贝赋值导致形参和实参的指针成员指向共同的存储单元。由此造成的后果是一旦被调用的函数返回,形参析构就必然会释放其指针所指向的存储单元,该存储单元可能会立刻被操作系统分配给其他程序,但本程序并不知道该存储单元被分配给其他存储单元,必然造成一个程序非法访问另一个内存单元;

/*
在本例中,void func,程序有两次析构输出,函数func返回前析构形参 y ,同时释放 y.p 和a.p 共用的内存,返回后该块内存又被分配给q,而对象 a 不知道该内崔已被释放,继续访问得到 a[0] = 8
*/
#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. 在非引用类型的形参对象包含指针数据成员时,必须进行深拷贝才能避免内存保护错误,即必须传递参数前为形参对象的指针分配新的存储单元,而后将实参对象的指针成员随之向的存储单元的内容复制到新的存储单元中;为了在传递参数时进行深度拷贝,必须将析构函数的参数类型定义为类或者类的引用;

/*
本程序定义构造函数 ARRAY( ARRAY &r)
在调用函数时实现深度拷贝赋值,
*/
#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
发布了52 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jzj_c_love/article/details/102527107