C++中指针一直是个不被人待见的东西,不仅是因为指针这个东西让人把关系搞不清楚,而且对指针new一个空间后,往往会忘记delete释放空间,这就让内存的泄漏不可避免的发生了。
如今有个auto_ptr(智能指针)来解决这个问题:
class A{
public:
A(){
cout << "constuctor" << endl;
}
~A(){
cout << "distuctor" << endl;
}
void func(){
cout << "I am a function" << endl;
}
void* operator new(size_t size){
cout << "size = " << size << endl;
cout << "void* operator new(size_t size)" << endl;
void *p = malloc(size);
return p;
}
void operator delete(void* p){
cout << "void operator delete(A* p)" << endl;
free(p);
}
};
int main()
{
auto_ptr<A> a(new A);
a->func();
(*a).func();
return 0;
}
运行结果如下:
这里auto_ptr本身是个类模板,auto_ptr<A>这就变成了一个模板类,a就是个模板类对象,这个对象就可以像一个对象指针一样对成员函数或者数据成员进行操作。而且发现这里并没有delete去释放,在a离开其栈空间时,他会自动调用delete去释放空间,这就省了我们很多麻烦。后面就通过对->和*的重载实现一个自己的auto_ptr。
class A{
public:
A(){
cout << "constuctor" << endl;
}
~A(){
cout << "distuctor" << endl;
}
void func(){
cout << "I am a function" << endl;
}
void* operator new(size_t size){
cout << "size = " << size << endl;
cout << "void* operator new(size_t size)" << endl;
void *p = malloc(size);
return p;
}
void operator delete(void* p){
cout << "void operator delete(A* p)" << endl;
free(p);
}
};
class Smt{
public:
Smt(A* p){
a = p;
}
~Smt(){
delete a;
}
A* operator->(){
return a;
}
A& operator*(){
return (*a);
}
private:
A* a;
};
int main()
{
Smt smt(new A);
smt->func();
(*smt).func();
return 0;
}
输出结果:
用Smt类的构造器实现auto_ptr对应的new操作,当Smt对象离开作用域时,自动调用析构器,实现了auto_ptr的自动delete的操作,同时通过重载->和*让对象表现的像个指针,可以对类A中的成员函数和数据成员进行操作。
最后说明一点:不要用auto_ptr,这个现在已经被抛弃了,那要用什么,以后再说。

605

被折叠的 条评论
为什么被折叠?



