走向 智能指針

知道智能指針很久了,最近改造一個c# 代碼,c#自動回收內存,那叫一個爽,c++卻沒有這個功能,但這個c#代碼內存使用情況複雜, 直接改成手動回收相當麻煩,於是 不得不使用智能指針


#include <iostream>
#include <memory>

class Segment
{
public:
	int x;
	int y;

	Segment(int _x, int _y)
	{
		x = _x;
		y = _y;
	}

	~Segment() {
		printf("delete segment\n");
	}
};

std::shared_ptr<Segment> func1()
{
	Segment* ps = new Segment(3,2);

	return std::shared_ptr<Segment>(ps);
	//return sps;
	// 如下代碼也是支持的,外部get()指針的時候要判斷下
	// return std::shared_ptr<Segment>(NULL);
	//return ps;

	// 注意,func1 返回 Segment *, 然後 內部 寫成以下代碼是不行的
	//std::shared_ptr<Segment> sps(ps);
	//return sps.get();
}

void func2()
{
	auto ps = func1();
	printf("xx\n");
	auto pps = ps.get();
	if (pps != NULL)
	{
		printf("%d\n", pps->x);
	}
	else
	{
		printf("failed \n");
	}
}
int main()
{
	func2();
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章