当多个指针指向同一个对象,其中一个指针delete后,剩下的指针便成了野指针,浪费内存。
例如:
int* a = new int(6);
int *p = a;
printf("p的地址为 :%x 值为: %d \n", p, *p);
delete a;
a = nullptr;
printf("p的地址为 :%x 值为: %d \n", p, *p);
return 0;
在引用计数中,每一个对象负责维护对象所有引用的计数值。当一个新的引用指向对象时,引用计数器就递增,当去掉一个引用时,引用计数就递减。当引用计数到零时,该对象就将释放占有的资源。
,
,
代码实现:
class t_count {
private:
int *_count;
public:
t_count() :_count(new int(1)) {};
t_count(t_count &tmp) {
_count = tmp._count;
++*tmp._count;
}
void operator=(t_count &tmp) {
if (--*_count == 0) {
delete _count;
}
_count = tmp._count;
++*tmp._count;
}
bool isonly() {
if (--*_count == 0)
return true;
else
return false;
}
bool iscopy(t_count &tmp) {
++*tmp._count;
if (--*_count == 0) {
delete _count;
_count = tmp._count;
++*tmp._count;
return true;
}
_count = tmp._count;
return false;
}
~t_count() {
if(--*_count==0){
delete _count;
_count == nullptr;
}
}
};
template<class T>
class smart_ptr {
private:
T *_data;
t_count *_c;
public:
smart_ptr() :_data(new T), _c(new t_count) {};
smart_ptr(T *tmp) :_data(tmp), _c(new t_count()) {};
smart_ptr(const smart_ptr<T> &tmp) {
_data = tmp._data;
_c = new t_count(*tmp._c);
}
smart_ptr& operator=(smart_ptr<T> &tmp) {
if (_c->iscopy(*tmp._c)) {
delete _data;
}
_data = tmp._data;
return *this;
}
T* get() {
return *_data;
}
~smart_ptr() {
if (_c->isonly()) {
cout << *_data<<" yes" << endl;
delete _data;
delete _c;
_data = nullptr;
_c = nullptr;
}
else {
cout << *_data <<" no!" << endl;
}
}
};
int main()
{
smart_ptr<int> a(new int(6));
smart_ptr<int> b = a;
smart_ptr<int> c = b;
smart_ptr<int> d(new int(5));
b = d;
return 0;
}
,结果如下:
输出的no,yes是在析构函数定义的,可以看出,当b=d后,执行return之后,调用d的析构函数,此时因为还有b和d共享一个对象,所以输出no,然后再执行c的析构函数,c此时是指向a的,所以输出6 no,之后调用b的析构、a的析构。
从结果上来看,一个简单的智能指针,就做好啦~。
此次更新,是更新以前贴在这得代码不完整,以及没有一些分析。 —2018.6.14