auto_ptr(已废弃)
废弃的原因:避免因潜在的内存问题导致程序崩溃
auto_ptr的对象支持拷贝,拷贝后原对象变得无效,再次访问原对象时会导致程序崩溃
#include <iostream>
#include <memory>
#include <string>
using namespace std;
int main()
{
auto_ptr<string> p1(new string("hello"));
auto_ptr<string> p2 = p1;//p1将所有权转让给p2,此时p1不再引用该字符串从而变成空指针
cout << *p1 <<endl; //编译通过,但是在运行时会崩溃
cout << *p2 <<endl;
system("pause");
return 0;
}
(auto_ptr 不能放在容器中的原因是:STL容器在分配内存的时候,必须要能够拷贝构造容器的元素。但是auto_ptr在拷贝构造的时候,会使原对象无效)。
.
.
.
unique_ptr (替代auto_ptr)
比auto_ptr更加安全,也可以放在容器中。
禁止拷贝,但是可以使用move()进行控制权限转移。
unique_ptr<string> p1(new