前一篇文章介绍了共享指针shared_ptr,这篇介绍另一种智能指针:unique_ptr。
1、创建
与shared_ptr不同,C++11并没有提供类似std::make_shared的标准库函数来返回一个unique_ptr,但是C++14提供了类似的库函数:std::make_unique,语法如下:
std::make_unique<类型>(参数列表)
依然以Person类为例:
class Person
{
public:
Person(const std::string& strName, int iAge) :m_strName(strName), m_iAge(iAge){}
~Person(){ std::cout << "Person析构, name=" << m_strName << std::endl; }
void PrintInfo(){ std::cout << "姓名:" << m_strName << ", 年龄:" << m_iAge << std::endl; }
private:
std::string m_strName;
int m_iAge;
};
主函数如下:
int _tmain(int argc, _TCHAR* argv[])
{
{
std::unique_ptr<Person> p1 = std::make_unique<Person>("ye", 30);
p1->PrintInfo();
}
system("pause");
return 0;
}
执行结果:
很简单!一旦p1的作用域消失,便会自动释放内存。