C++成员是指针的处理(一)

//
//  A.h
//  Memory
//
//  Created by xiangchenyu on 13-3-10.
//  Copyright (c) 2013年 xiangchenyu. All rights reserved.
//

#ifndef Memory_A_h
#define Memory_A_h

class A
{
public:
    A(int size):size(0),pStr(0)
    {
        this->size = size;
        this->pStr = new int(size);
    }
    ~A()
    {
        if(this->pStr)
            delete []pStr;
    }
    void setValue(int index,const int& value)
    {
        if(index<this->size)
             pStr[index] = value;
    }
    
    int getValue(int index) const
    {
        if(index<this->size)
            return pStr[index];
        else
            return int();
    }
public:
//拷贝构造函数
    A(const A& a):size(a.size),pStr(0)
    {
        if(pStr)
        {
            delete []pStr;
            pStr = NULL;
        }
        if (size)
        {
            pStr = new int[size];
            for (int i = 0; i <size; ++i)
            {
                setValue(i,a.getValue(i));
            }
        }
    }
//赋值函数
    const A& operator=(const A& a)
    {
        if(this == &a)
            return *this;
        this->size = a.size;
        
        if(pStr)
        {
            delete []pStr;
            pStr = NULL;
        }
        
        if (size)
        {
            pStr = new int[size];
            for (int i = 0; i <size; ++i)
            {
                setValue(i,a.getValue(i));
            }
        }
        return *this;
    };
    
private:
    int size;
    int* pStr;
};


#endif

调用的时候:

    A a(10);
    a.setValue(0, 555);
    A a1 = a;
    
    NSLog(@"a1-->%d",a1.getValue(0));

输出结果:555


C++的指针成员如果没有NEW,后果不看设想,如下所示


Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->class Table{
Name * p;
size_t sz;

publish:

Table(size_t s = 15){p = new Name[sz=s];}
~Table(){delete[]p ;}

......
}

void h()
{
Table t1;
Table t2 = t1;
Table t3;
t3 = t2;
}

在h()结束时,默认构造函数调用了2次,而析构函数被调用了3次,为何?

Tablet1; 调用1次默认构造函数

Tablet2=t1;默认的对象的赋值操作,按成员赋值,其中关于指针p,仅仅是将t1.p赋值给t2.p,即t2.p = t1.p,并无内存分配。对象t1和t2的p指针均指向同一块内存。

Tablet3; 调用1次默认构造函数

t3=t2;原t3.p指针被t2.p覆盖,此时t3.p同样指向对象t1和t2的p指针的同一块内存。注意:t3原分配给p的内存由于没有指针指向,无法利用,造成存储浪费。

h()结束,对象t1,t2,t3的析构函数调用,此时对t1,t2,t3的指针p所指的同一块存储进行了三次删除,非常危险,导致的结果是无发预料的,很可能灾难性的。

因此明确定义类的复制构造函数(拷贝构造函数)和赋值预算可避免这样的错误。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值