转载请注明出处:
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.
大家可以看上一篇文章,这里已经避免了多次赋值拷贝造成的内存问题。推荐这一种方式。