c++精巧cookie

項目暫時告一段落,有幾個比較有意思的代碼,拿出來然讓大家指點下。這一段小小cookie雖說通俗淺顯簡單易懂,但確實很好用很實用。

//cookie.h
#ifndef  _COOKIE_
#define _COOKIE_

#include <string>
#include <map>
#include <pthread.h>
using namespace std;

class Cookie
{
public:
	string& operator()(string key);
	Cookie();
	~Cookie();
	
private:
	pthread_mutex_t cookie_mutex_;
	map<string, string> cookie_map_;
};

#endif //_COOKIE_

//cookie.cc
#include "cookie.h"

Cookie::Cookie()
{
	pthread_mutex_init(&cookie_mutex_, 0);
}

Cookie::~Cookie()
{
	pthread_mutex_destroy(&cookie_mutex_);
}

string& Cookie::operator()(string key)
{
	map<string, string>::iterator it;
	
	pthread_mutex_lock(&cookie_mutex_);
	it = cookie_map_.find(key);
	if (it == cookie_map_.end())
	{
		cookie_map_.insert(make_pair(key, ""));
		it = cookie_map_.find(key);
	}
	pthread_mutex_unlock(&cookie_mutex_);
	
	return it->second;
}


若是嫌cookie存儲的類型太過單一,可以自行擴展下。

下面給出一個測試程序:

//cookie_test.cc
#include <iostream>
#include "cookie.h"

int main(int argc, char** argv)
{
	Cookie cookie;
	//存儲變量
	cookie("name") = "chris";
	cookie("school") = "whu;

	cout << "cookie(\"school\") = " << cookie("school") << endl;
	cout << "cookie(\"name\") = " << cookie("name") << endl;
	
	//修改變量值
	cookie("name") = "thor";
	cout << "cookie(\"name\") = " << cookie("name") << endl;
	
	return 0;
}


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