以下是我怎么可能有某种形式的自动内存管理C++中的草图:C内存管理
template<class T>
class Ptr{
public:
/* Some memory management stuff (ref counting etc.)
as Ptr object is initialized */
Ptr(...) { .. }
/* Manage reference counts etc.
as Ptr object is copied -- might be necessary
when Ptr is passed to or returned from functions */
Ptr<T>& operator=(..) { .. };
/* Do memory management stuff
when this "Pointer" object is destroyed. */
~Ptr() { .. }
private:
/* Pointer to main object */
T* object;
}
class Obj{
public:
static Ptr<Obj> newObj(..) { return Ptr<Obj>(new Obj(..)); }
private:
/* Hide constructor so it can only be created by newObj */
Obj(..) { .. }
/* some variables for memory management routines */
int refcnt;
..
}
这样,最终用户从来没有打电话给新的或malloc的,而是可以调用Obj.newObj(..)。
不过,我敢对我怎么可能会做同样的事情为C.
难倒它不必完全像上面,但我不想去关心内存管理这并不重要。
我觉得我遇到的最大问题是,当C中的变量超出范围时,我没有真正的'析构函数'可以发信号通知我该变量已超出范围。
你为什么要创建自己的智能指针? – delnan
如果你想要智能指针,你不应该使用C. – Pubby