0
点赞
收藏
分享

微信扫一扫

初识智能指针

楚木巽 2022-02-26 阅读 86
c++

初识智能指针

什么是智能指针

智能指针是行为类似于指针的类对象。

为什么要使用智能指针

在函数内使用常规普通指针时,容易因为忘记释放内存、异常使函数直接终止等原因造成内存泄露;考虑到类对象可以在对象过期时,析构函数会释放指向的内存,所以我们考虑将指针对象化,由此引出智能指针。当然,知道智能指针的目的后,我们得注意,智能指针的实质是行为类似于指针的类对象

三个智能指针模板

分别是auto_ptr, unique_ptr, shared_ptr。
auto_ptr已被C++11摒弃,但它已使用多年;且编译器不支持其他两种智能指针时,auto_ptr是唯一的选择。

格式

要创建智能指针对象,必须包含头文件memory;模板位于名称空间std中。

#include <iostream>
#include <string>
#include <memory>

class Report
{
private:
	std::string str;
public:
	Report(const std::string s) : str(s){
		std::cout << "Object created!\n";
	}
	~Report(){
		std::cout  <<  "Object deleted!\n";
	}
	void comment()const{
		std::cout << str << std::endl;
	}
};

int main()
{
	{
		std::auto_ptr<Report> ps (new Report("using auto_ptr"));
		ps->comment();
	}
	{
		std::shared_ptr<Report> ps (new Report("using shared_ptr");
		ps->comment();
	}
	{
		std::unique_ptr<Report> ps (new Report("using unique_ptr");
		ps->comment();
	}
	return 0;
}

参考书籍

举报

相关推荐

0 条评论