- C++11特性里面引入了很多智能指针,其中就包括unique_ptr,智能指针的作用是管理一个指针以防止指针忘记释放而造成内存泄露。
- unique_ptr是一个类,当超出了类的作用域,类会自动调用析构函数,析构函数会自动释放资源。其原理就是在函数结束时自动释放内存空间。
- unique_ptr的头文件为memory
#include<iostream>
#include<memory>
using namespace std;
class Dog{
public:
Dog(){
cout<<"Nameless dog created."<<endl;
s1="nameless";
}
Dog(string name){
cout<<"Dog is created:" << name<<endl;
s1=name;
}
void foo(){
cout<<"Dog "<<s1<<" rules. "<<endl;
}
~Dog(){
cout<<"Dog is destoryed:"<<s1<<endl;
}
private:
string s1;
};
void test()
{
unique_ptr<Dog> pd(new Dog("jinmao"));
pd->foo();
}
int main()
{
test();
return 0;
}
无法同时用多个智能指针指向同一个对象,如下程序报错
#include<iostream>
#include<memory>
using namespace std;
class Dog{
public:
Dog(){
cout<<"Nameless dog created."<<endl;
s1="nameless";
}
Dog(string name){
cout<<"Dog is created:" << name<<endl;
s1=name;
}
void foo(){
cout<<"Dog "<<s1<<" rules. "<<endl;
}
~Dog(){
cout<<"Dog is destoryed:"<<s1<<endl;
}
private:
string s1;
};
void test()
{
unique_ptr<Dog> pd(new Dog("jinmao"));
unique_ptr<Dog> pd1;
pd1=pd;//程序报错,应该保证同一时间内只有一个智能指针可以指向该对象
}
int main()
{
test();
return 0;
}