【问题标题】:Example of UUID generation using Boost in C++在 C++ 中使用 Boost 生成 UUID 的示例
【发布时间】:2011-03-15 22:34:59
【问题描述】:

我只想生成随机的 UUID,因为我的程序中的实例具有唯一标识符非常重要。我查看了Boost UUID,但无法生成 UUID,因为我不明白要使用哪个类和方法。

如果有人能给我任何如何实现这一目标的例子,我将不胜感激。

【问题讨论】:

    标签: c++ boost uuid boost-uuid


    【解决方案1】:

    一个基本的例子:

    #include <boost/uuid/uuid.hpp>            // uuid class
    #include <boost/uuid/uuid_generators.hpp> // generators
    #include <boost/uuid/uuid_io.hpp>         // streaming operators etc.
    
    int main() {
        boost::uuids::uuid uuid = boost::uuids::random_generator()();
        std::cout << uuid << std::endl;
    }
    

    示例输出:

    7feb24af-fc38-44de-bc38-04defc3804de

    【讨论】:

    • 你如何将它分配给一个字符串?因为我对每个实例都有一个共同的基础,我需要将 UUID 连接到一个基础。再次感谢!
    • @nik:使用streaming support - 有一个stringstream 示例。或者让boost::lexical_cast&lt;std::string&gt;(uuid) 为你做这件事。
    • 至于双括号:第一个构造random_generator的实例,第二个在该实例上使用operator()。如果要生成多个 uuid,则应保存生成器并在其上调用 operator()random_generator rg; uuid ui = rg();
    • @Nikola : 使用 boost::uuids::to_string(uuid) 对 uuid 进行字符串化
    • @GeorgFritzsche 总之,准确的时间和机器的个人网络地址是唯一的。因此,我认为它可能是散列函数的好键。我以后不需要明确的价值观。但是你的想法给我带来了一个想法。使用时间和网络地址作为随机数生成器的种子可能会很好。
    【解决方案2】:

    Georg Fritzsche 的回答还可以,但可能有点误导。如果您需要多个 uuid,则应该重用生成器。 也许这样更清楚:

    #include <iostream>
    
    #include <boost/uuid/uuid.hpp>            // uuid class
    #include <boost/uuid/uuid_generators.hpp> // generators
    #include <boost/uuid/uuid_io.hpp>         // streaming operators etc.
    
    
    int main()
    {
        boost::uuids::random_generator generator;
    
        boost::uuids::uuid uuid1 = generator();
        std::cout << uuid1 << std::endl;
    
        boost::uuids::uuid uuid2 = generator();
        std::cout << uuid2 << std::endl;
    
        return 0;
    }
    

    【讨论】:

    • 为什么要重复使用生成器?这是性能优化还是安全提示?
    • 如果使用新的生成器导致唯一性问题,这将不是一个很好的通用唯一 ID。
    • @Saneeshkumar 这是一个“通用唯一标识符”而不是“这个生成器唯一标识符”,这是有原因的。
    • 向我学习并使生成器线程本地化。它们的种子非常昂贵
    • 官方文档仅出于性能考虑而鼓励重用 random_generator,而不是出于安全考虑。 “根据平台的不同,初始化生成器可能会产生设置成本,因此如果可以的话,请计划重用它”来源Boost uuid 1.70.0
    猜你喜欢
    • 2014-08-13
    • 2018-12-20
    • 1970-01-01
    • 2019-09-29
    • 2012-01-18
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多