Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using libuuid / uuid-dev with C++11

Tags:

c++

c++11

I'm looking to use libuuid with a C++11 program. However, I think I might be going about this incorrectly. According to uuid.h, the uuid_t is a unsigned char array of 16 items (expected). My approach to building a std::string with this was as follows:

uuid_t uuidObj;
uuid_generate(uuidObj);
std::string aString;

for (auto i = 0; i < 16; ++i)
{
   aString += uuidObj[i];
}

I know that this can't be the most approriate solution (while avoiding a malloc in C++11, yikes!), any tips from y'all?

like image 720
jackyalcine Avatar asked Apr 29 '26 08:04

jackyalcine


1 Answers

You can initialize the string within the constructor itself, passing the begin and end pointers as iterators.

uuid_t uuidObj;
uuid_generate(uuidObj);
std::string aString{ uuidObj, uuidObj + 16 };

The Pragmatic Croissant is also correct that you may free yourself of worrying about the array size by using the more C++11 idiomatic:

std::string aString{ std::begin(uuidObj), std::end(uuidObj) };

Also, your code in the question only copies the first 15 characters.

like image 121
Drew Dormann Avatar answered Apr 30 '26 20:04

Drew Dormann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!