C++基础(十一)智能指针之unique_ptr

前一篇文章介绍了共享指针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的作用域消失,便会自动释放内存。

2、所有权转移及内容清空<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值