C++成员是指针的处理(二)-引用技术

转载请注明出处:

http://blog.csdn.net/xcysuccess3/

在学习完IOS之后,觉得C++的拷贝构造函数和赋值函数可以用IOS方式实现。节约内存和时间。试着写了一下

B.h

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

#ifndef Memory_B_h
#define Memory_B_h

class A
{
private:
    int size;
    int* pStr;
    int* count; //作为引用计数,此处应该使用指针,使所有的对象,都共享同一块内存地址
    
public:
    A(int size):size(0),pStr(0),count(new int)
    {
        *count = 1;
        this->size = size;
        this->pStr = new int(size);
    }
    ~A()
    {
        Release();
    }
    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(a.pStr),count(new int)
    {
        ++(*count);
    }
    //赋值函数
    const A& operator=(const A& a)
    {
        if(this == &a)
            return *this;
        //类同IOS,旧对象释放,新对象引用计数+1,赋值给旧对象
        Release();
        
        this->size = a.size;
        this->pStr = a.pStr;
        
        ++(*count);
        
        return *this;
    };
private:
    void Release()
    {
        (*count)--;
        if((*count) == 0)
        {
            if(this->pStr)
            {
                delete []pStr;
                pStr = NULL;
            }
            delete count;
            count = NULL;
        }
       
    }

};

#endif

函数调用的地方:

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

结果仍然是555.

大家可以看上一篇文章,这里已经避免了多次赋值拷贝造成的内存问题。推荐这一种方式。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值