为了防止资源泄露,请使用RAII (resource Acquisition is initialization),他们在构造函数中或的资源并在析构函数中 释放资源。
应用模板(类):
shared_ptr ;
shared_ptr 的构造函数已经声明为 explicit ,防止隐式类型转换。
用例:
#include<iostream>
#include <string >
#include <memory>
using namespace std ;
int main()
{
string *Pts= new string("hi");
shared_ptr <string > p1(Pts);
if (p1&& p1->empty() ) //判断p1 是否为空,是否指向一个空字符串
{
*p1 = "hi"; //解引用
}
cout<< *p1<<endl;
}