您的位置:首页 > 编程语言 > C语言/C++

C++语法基础--智能指针

2013-07-22 09:41 429 查看
1.智能指针准备知识:new关键字定义的指针,如果不用delete关键字删除,即使指针超出作用域范围,该指针也不会被删除

Example:

先给出一个在析构函数没有删除指针的类

class A

{

public:

A(int *pt):p(pt)

{

}



private:

int *p;

};



int main()

{

int *a=new int(1);

{

A b(a);

}



cout<<*a<<endl;//1



return 0;

}

在A的析构函数中删除指针

class A

{

public:

A(int *pt):p(pt)

{

}

~A()

{

delete p;

}

private:

int *p;

};

int main()

{

int *a=new int(1);

{

A b(a);

}



cout<<*a<<endl;//随机数,因为对象b超出了作用域,自动调用了对象b的析构函数。



return 0;

}

2.实现智能指针基本步骤

*复制构造函数将旧对象复制到新对象是,将记数加1

*赋值操作符将左操作数的使用记数减1,并将右操作数的使用记数加1,如果左操作数的使用记数减至0,赋值操作符必须删除它所指向的对象


*析构函数将使用记数减1,如果使用记数减至0,删除基础对象

Tips:

智能指针的关键在于设置一个类专用于保存指针。



注:绿色代码部分只是为了验证智能指针是否工作正常,并非智能指针类必须的。

Example:

class count_pointer

{

friend class smart_pointer;

private:

count_pointer(int *p):pt(p),count(1)

{


}


~count_pointer()

{

cout<<"~count_pointer()"<<endl;


}

int *pt;

int count;

};

class smart_pointer

{

public:

smart_pointer(int *pt):cp(new count_pointer(pt))

{

}



smart_pointer(smart_pointer& other):cp(other.cp)

{

++cp->count;


}

smart_pointer& operator=(smart_pointer& other)

{

++other.cp->count;

if(--cp->count==0)

{

delete
cp;

}


cp=other.cp;

return *this;


}

~smart_pointer()

{



if(--cp->count==0)

{


delete cp;

}


}

void print()

{

cout<<"count_pointer::count "<<cp->count<<endl;

cout<<"count_pointer::*pt "<<*(cp->pt)<<endl;

}

private:

count_pointer *cp;

};





int main()

{

int *p=new int(100);

smart_pointer sp1(p);

cout<<"smart_pointer sp1:"<<endl;

sp1.print();

cout<<endl;



smart_pointer sp2(sp1);

cout<<"after using copy constructor:"<<endl;

cout<<"smart_pointer sp1:"<<endl;

sp1.print();

cout<<endl;



cout<<"smart_pointer sp2:"<<endl;

sp2.print();

cout<<endl;

int *p1=new int(200);

smart_pointer sp3(p1);

sp1=sp3;

cout<<"after using assign operator:"<<endl;

cout<<"smart_pointer sp1:"<<endl;

sp1.print();

cout<<endl;



cout<<"smart_pointer sp2:"<<endl;

sp2.print();

cout<<endl;



cout<<"smart_pointer sp3:"<<endl;

sp3.print();

cout<<endl;

return 0;

}

运行结果:


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: