64,685
社区成员
发帖
与我相关
我的任务
分享
STL中的auto_ptr指针是为了解决内存泄漏问题而设计的。它严格限制了指针拥有对指向对象的所有权。
auto_ptr指针和普通指针的差别在于对指向对象所有权的处理不同。
auto_ptr指针是“传递”所有权,而普通指针是“共享”所有权。
测试一下就知道了啊:
#include <memory>
#include <string>
#include <cassert>
#include <iostream>
using namespace std;
int main()
{
auto_ptr<string> pstr_auto1(new string("hello word")); //已有智能指针
//下面打算用pstr_auto1初始化pstr_auto2
//auto_ptr <string> pstr_auto2(pstr_auto1); //方法一
//auto_ptr <string> pstr_auto2(pstr_auto1.release()); //方法二
auto_ptr <string> pstr_auto2(pstr_auto1.get()); //方法三 cout<<*pstr_auto2<<endl;
cout<<*pstr_auto1<<endl;
return 0;
}
auto_ptr是传递使用权的
方法3没有问题;
方法1,2都会抛出异常的,