#include <memory.h>
using namespace std;
class Done {
string myS;
public:
Done(const string &s):myS(s){ };
void Doit(){ cout << myS << endl; };
};
int main(int argc, const char * argv[]) {
/**
* 三种智能指针语法
* 对应头文件 memory.h
* new double 返回指针指向新分配内存块(形参)
* 删除了 delete
* new[] 不能使用 auto_ptr和shared_ptr
* new、new[] unique_ptr 都可以处理
*/
//1、auto_ptr 如果两个智能指针相互赋值,可能崩溃,应该用深复制
auto_ptr<double> ap_d(new double(20.1f));
double t = *ap_d;
cout << "double =" << t << endl;
auto_ptr<string> ap_s(new string("dsfs"));
auto_ptr<string> ap_s2(new string("dsfs2"));
string s(*ap_s);
cout << "string =" << s << endl;
ap_s2 = ap_s; //不警告
//2、unique_ptr 如果两个智能指针相互赋值,首先编译错误
unique_ptr<double> up_d(new double(30));
unique_ptr<string> up_s(new string("unique_ptr"));
unique_ptr<string> up_s2(new string("unique_ptr2"));
//up_s2 = up_s; 语法警告了
up_s2 = move(up_s);
//3、shared_ptr 适合多个对象指向同一指针
shared_ptr<double> sp_d(new double(40.2f));
shared_ptr<string> sp_s(new string("shared_ptr"));
shared_ptr<string> sp_s2(new string("shared_ptr2"));
sp_s2 = sp_s;
//例子
{
auto_ptr<Done> ap_D(new Done("123456"));
ap_D->Doit();
}
{
unique_ptr<Done> up_D(new Done("asdfg"));
up_D->Doit();
}
{
shared_ptr<Done> sp_D(new Done("nbvcx"));
sp_D->Doit();
}
return 0;
}