スマートポインタ:
(1)スマートポインタはメモリを自動的に解放できるため、メモリスペースを解放するために手動で削除する必要はありません。
(2)スマートポインタは実際にはテンプレートクラスであり、そのデータ内部タイプはauto_ptr <...>です。 、例:auto_ptr ptr(new int); auto_ptr ptr = newint;にすることはできません。
コード:
#include <iostream>
#include <memory>//智能指针的头文件
using namespace std;
class A
{
public:
A(int a)
{
cout << "A()..." << endl;
this->a = a;
}
void func() {
cout << "a = " << this->a << endl;
}
~A() {
cout << "~A()..." << endl;
}
private:
int a;
};
class MyAutoPtr//自定义智能指针
{
public:
MyAutoPtr(A * ptr)
{
this->ptr = ptr;//ptr = new A(10)
}
~MyAutoPtr() { //析构函数实现释放内存空间
if (this->ptr != NULL) {
cout << "delte ptr" << endl;
delete ptr;
this->ptr = NULL;
}
}
A* operator->()//当自定义智能指针时,->需要被重载
{
return this->ptr;
}
//返回A的引用来访问*ptr
A& operator*()
{
return *ptr;
}
private:
A *ptr;//注意自定义智能指针时,不能是void *ptr
};
//测试C++自身的智能指针
void test1()
{
#if 0
A* ap = new A(10);
ap->func();
(*ap).func();
delete ap;
auto_ptr<int> ptr(new int);
#endif
auto_ptr<A> ptr(new A(10));
ptr->func();
(*ptr).func();
}
void test2()
{
MyAutoPtr my_p(new A(10));
my_p->func(); //my_p.ptr -> func()
(*my_p).func(); // *ptr.func()
}
int main(void)
{
//test1();
test2();
return 0;
}