c++ 小知识点三

版权声明:www.gudianxiaoshuo.com (古典小说网) 今日头条号: 古典古韵古典小说、讨厌编程 https://blog.csdn.net/shuilan0066/article/details/82852766

1、单例模式定义

// "TypeName type" will be lazily created on the first time it's accessed

#ifndef BASE_MEMORY_SINGLETON_H_
#define BASE_MEMORY_SINGLETON_H_


namespace nbase
{

#define SINGLETON_DEFINE(TypeName)				\
static TypeName* GetInstance()					\
{												\
	static TypeName type_instance;				\
	return &type_instance;						\
}												\
												\
TypeName(const TypeName&) = delete;				\
TypeName& operator=(const TypeName&) = delete

}



#endif // BASE_MEMORY_SINGLETON_H_

示例1:

class ThreadMap
{
public:
	SINGLETON_DEFINE(ThreadMap);
	static bool AquireAccess();

	bool RegisterThread(int self_identifier);
	bool UnregisterThread();
	int QueryThreadId(const FrameworkThread *thread);
	std::shared_ptr<MessageLoopProxy> GetMessageLoop(int identifier) const;
	FrameworkThread* QueryThreadInternal(int identifier) const;

private:
	ThreadMap() { }
	NLock lock_;
	std::map<int, FrameworkThread*> threads_;
};

示例2

namespace shared
{
// IPC
class IPCManager
{
public:
	SINGLETON_DEFINE(IPCManager);
	IPCManager();
	~IPCManager();
	bool CreateSharedMemory(const std::wstring &tag, const std::string &data);
	void DestroySharedMemory(const std::wstring &tag);

private:
	std::map<std::wstring, HANDLE>		shared_memory_handle_map_;
	nbase::NLock						lock_;
};
}//namespace shared

猜你喜欢

转载自blog.csdn.net/shuilan0066/article/details/82852766