C++创建UUID的两种方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
std::string newGUID()
{
	char buf[50];
	memset(buf, 0, sizeof(buf));
	GUID guid;
	if (S_OK == ::CoCreateGuid(&guid)) {
		sprintf_s(buf, 50, "{%08X-%04X-%04x-%02X%02X-%02X%02X%02X%02X%02X%02X}"
			, guid.Data1
			, guid.Data2
			, guid.Data3
			, guid.Data4[0], guid.Data4[1]
			, guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5]
			, guid.Data4[6], guid.Data4[7]);
	}
	return std::string(buf);
}

使用BOOST的话:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>  
#include <boost/lexical_cast.hpp>

std::string getUUID()
{
	boost::uuids::random_generator rgen;						//随机生成器  
	boost::uuids::uuid a_uuid = rgen();							//生成一个随机的UUID  
	std::string str = boost::lexical_cast<std::string>(a_uuid); //uuid转换到字符串
	return str;
}