#include<stdio.h>
#include<iostream>
#include<memory>
using namespace std;
class report
{
private:
string str;
public:
report(const string s) : str(s)
{
cout << "Object created!\n";
}
~report()
{
cout << "Object delected!\n";
}
void comment() { cout << str << endl;}
};
int main()
{
{
auto_ptr<report> ps(new report("using auto_ptr"));
ps->comment();
}
cout << endl;
{
shared_ptr<report> ps(new report("using shared_ptr"));
ps->comment();
}
cout << endl;
{
unique_ptr<report> ps(new report("using shared_ptr"));
ps->comment();
}
}
结果
Object created!
using auto_ptr
Object delected!
Object created!
using shared_ptr
Object delected!
Object created!
using shared_ptr
Object delected!
注意事项
auto_ptr<string> ps (new string("Ihave a try“));
auto_ptr<string> vocation;
vocation = ps;
对于上述代码,怎么防止同一对象被释放两次
1、定义赋值运算符,使之执行深复制。
2、建立所有权(ownership)概念,对于特定的对象,只能有一个指针可拥有它,这样拥有对象的智能指针的构造函数会删除该对象。让赋值操作转让所有权。这就是应用于auto_ptr和uniique_ptr的策略,但unique_ptr的策略更严格。
3、创建智能更高的指针,跟踪引用特定的智能指针数。这称为引用计数(reference counting)。例如,赋值时,计数将加1,而指针过期时,计数将减1.仅当最后一个指针过期时,才调用delete。
shared_ptr采用该策略。
#include<stdio.h>
#include<iostream>
#include<memory>
using namespace std;
int main()
{
auto_ptr<string> films[5] =
{
auto_ptr<string> (new string("num 1")),
auto_ptr<string> (new string("num 2")),
auto_ptr<string> (new string("num 3")),
auto_ptr<string> (new string("num 4")),
auto_ptr<string> (new string("num 5"))
};
auto_ptr<string> pwin;
pwin = films[2];
for(int i = 0;i<5;i++)
cout << *films[i] << endl;
cout << "the *pwin = " << *pwin << endl;
cin.get();
return 0;
}
运行结果
num 1
num 2
段错误
使用shared_ptr代替auto_ptr
运行结果
num 1
num 2
num 3
num 4
num 5
the *pwin = num 3
使用unique_ptr代替auto_ptr,编译器因下述代码错误:
pwin = films[2];
所以unique_ptr比auto_ptr安全
选择智能指针
如果一个程序要使用多个指向同一个对象的指针,应该选择shared_ptr。
如果程序不需要多个指向同一个对象,则可使用uunique。
auto_ptr建议不要使用,毕竟被c++11放弃了。