#include<iostream>usingnamespace std;template<typenameT>classcomplex{private:
T re;
T im;public:complex(const T r,const T i):re(r),im(i){
cout <<"init complex"<< endl;}constvoidprint(){
cout << re <<" + "<< im <<"i"<< endl;}~complex(){
cout <<"free complex"<< endl;}};intmain(){
complex<int>* p =new complex<int>(10,10);
p->print();delete p;return0;}
结果: 容易泄露内存,比如 忘记写 或者 出现异常
#include<iostream>usingnamespace std;template<typenameT>classcomplex{private:
T re;
T im;public:complex(const T r,const T i):re(r),im(i){
cout <<"init complex"<< endl;}constvoidprint(){
cout << re <<" + "<< im <<"i"<< endl;}~complex(){
cout <<"free complex"<< endl;}};voidtest(){// 运行时出错}intmain(){
complex<int>* p =new complex<int>(10,10);
p->print();test();// 运行时出错delete p;// delete 不执行return0;}
2. C++ 98 的智能指针 auto_ptr (缺点:不能用于数组)
开辟一个放在栈空间的指针,在作用域完后释放 new 的对象,不需要使用 delete 释放对象
#include<iostream>usingnamespace std;template<typenameT>classcomplex{private:
T re;
T im;public:complex(const T r,const T i):re(r),im(i){
cout <<"init complex"<< endl;}constvoidprint(){
cout << re <<" + "<< im <<"i"<< endl;}~complex(){
cout <<"free complex"<< endl;}};intmain(){
cout <<"start"<< endl;{
auto_ptr<complex<double>>p(new complex<double>(1.0,1.0));
p->print();}
cout <<"end"<< endl;return0;}
3. 自己实现一个简单的 C++ 98 的智能指针
#include<iostream>usingnamespace std;template<typenameT>classcomplex{private:
T re;
T im;public:complex(const T r,const T i):re(r),im(i){
cout <<"init complex"<< endl;}constvoidprint(){
cout << re <<" + "<< im <<"i"<< endl;}~complex(){
cout <<"free complex"<< endl;}};template<typenameT>classSmartPointer{private:
T* sPointer;public:SmartPointer(T *p):sPointer(p){}~SmartPointer(){if(sPointer ==nullptr){return;}delete sPointer;}// 关键:重定义运算符 ->, 使对象能调用指针里的方法
T*operator->(){return sPointer;}};intmain(){// 系统的智能指针
cout <<"system_smart_pointer_start"<< endl;{
auto_ptr<complex<double>>p(new complex<double>(1.0,1.0));
p->print();}
cout <<"system_smart_pointer_end"<< endl;// 自定义的智能指针
cout <<"defined_ourselves_start"<< endl;{
SmartPointer<complex<double>>p(new complex<double>(1.0,1.0));
p->print();}
cout <<"defined_ourselves_end"<< endl;return0;}