//智能指针是一种类派生出的对象,能够在离开代码块的时候,自动delete掉new出的空间,以防止内存泄露
/*
auto_ptr :(已经被C++11摒弃)建立所有权概念(ownership)
ownership:对于特定的对象,只有一个智能指针可以拥有它,所以只有拥有对象的智能指针的
析构函数会删除该对象。 赋值操作可以转让所有权
unique_ptr : 策略上与 auto_ptr 相同,但是unique_ptr 更严格。
shared_ptr : 跟踪 引用特定对象的智能指针 的个数,赋值时,计数+1,指针过期时,计数-1。
则仅当最后一个指向特定对象的指针过期时,才会调用delete。
*/
/*
智能指针的构造函数,被explict修饰,不允许 隐式类型 转换,操作符的两个操作数类型必须匹配。
例:
shared_ptr<double> pd;
double * p_reg = new double;
pd = p_reg; // 不允许,不能隐式类型转换
pd = shared_ptr<double>(p_reg); // 允许
shared_ptr<double> pshared = p_reg; // 不允许,不能隐式类型转换
shared_ptr<double> pshared(p_reg); // 允许
*/
#include<iostream>
#include<string>
#include<memory>
using namespace std;
class Report{
private:
string str;
public:
Report(string s):str(s){
cout<<"Object created"<<endl;
}
~Report(){
cout<<"Object deleted!"<<endl;
}
void comment() const {
cout<<str<<endl;
}
};
int main(void){
{
auto_ptr<Report> pa (new Report("using auto_ptr"));
pa->comment();
}
{
shared_ptr<Report> ps (new Report("using shared_ptr"));
ps->comment();
}
{
unique_ptr<Report> pu (new Report("using unique_ptr"));
pu->comment();
}
return 0;
}
C++之智能指针 (一 )
最新推荐文章于 2024-03-27 21:36:52 发布