首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

智能指针有关问题~

2013-07-04 
智能指针问题~~~~请教:智能指针,其的思想是不是为了记录类的实例或对象的个数。一个独立的指针(智能指针)。

智能指针问题~~~~
请教:
智能指针,其的思想是不是为了记录类的实例或对象的个数。
一个独立的指针(智能指针)。
也是为了防止内存泄漏,方便的管理内存。大概是这意思么?
以下是简单的代码:
#include <iostream>
using namespace std;
//智能指针类
class B
{
private:
friend class A;
int *ip;
size_t use;

B(int *p):ip(p), use(0){}
~B()
{
cout<<"析构类B\n";
}
};
//--------------------------------
class A
{
private:
B *ptr;
int val;
public:
A(int *p, int i):ptr(new B(p)), val(i){++ptr->use;}
A(const A &a):ptr(new B(*a.ptr)),val(a.val)

++ptr->use; 
}
A& operator = (const A &a)
{
ptr = new B(*a.ptr);
val = a.val;
++ptr->use;
return *this;
cout<<"operator\n";
}
~A()

if(ptr->use != 0)
{
delete ptr; 
--ptr;
}
cout<<"析构类A\n";
}
};

int main(void)
{
int i = 1;
A a(&i, 2);
A f(a);
a = f;
return false;
}

大概是这意思么?? 智能指针 类 内存
[解决办法]


//测试智能指针(一种表现行为是指针的智能型对象)
namespace TestSmartPoint
{
template<class T>
class CountedPtr
{
public:
explicit CountedPtr(T *p = NULL):ptr(p), count(new int(1)) {}
CountedPtr(const CountedPtr<T> &p):ptr(p.ptr), count(p.count)
{
++(*count);
}
~CountedPtr()
{
dispose();
}
CountedPtr<T>& operator= (const CountedPtr<T> &p)
{
if (this != &p)
{
dispose();
ptr = p.ptr;
count = p.count;
++(*ptr);
}
return *this;
}

T& operator*()
{
return *ptr;
}
T* operator->()
{
return ptr;
}
private:
T *ptr;
int *count;

void dispose()
{
if (--(*count) == 0)
{
delete count;
count = NULL;
delete ptr;
ptr = NULL;
}
}
};
}

void TestMySmartPoint()
{
using namespace TestSmartPoint;
CountedPtr<int> pInt(new int(11));
CountedPtr<int> pInt2(pInt);

}

[解决办法]
我的理解是:new一个时,count+1,然后delete 的时候判断,但是复制构造函数,为什么不new? 如果是对象是new的话,可能会有问题,
你提到的这个是关于深浅复制的问题,你说的那种是深复制,就没必要用智能指针了,在深度复制的时候采用智能指针也很优雅,还不用开辟那么多的空间
http://baike.baidu.com/view/1391603.htm
看下智能指针百度是怎么讲的

热点排行
Bad Request.