c++ primer 12.1.4節練習(自定義 shared_ptr的刪除器)

12.14

#include <iostream>  
#include <string>
#include <vector>
#include <memory>
using namespace std;

string destination = "目的";
string connection = "連接";

string Connect(string *) //獲得一個連接
{
	cout << "獲得一個連接" << endl;
	string temp = "連接1";
	return temp;
}

void disconnect(string test)//關閉一個連接
{
	test.clear();
	cout << "關閉連接" << endl;
}

void end_connect(string *p)//結束一個連接
{
	disconnect(*p);
}

void f(string &d)
{
	string c = Connect(&d);
	cout << c << endl;
	shared_ptr<string>p(&c, end_connect);
}

int main()
{
	f(connection);//即,首先connection進入Connect,c被置爲“連接1”
				  //退出f之後c被銷燬,而connection也被end_connect給清空
	system("pause");
	return 0;
}


12.15

更新中...............

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章