static counter in c++

前端 未结 5 1783
太阳男子
太阳男子 2020-12-31 11:25

I\'m trying to create a Data class whose objects each hold a unique ID.

I want the 1st object\'s ID to be 1, the 2nd to be 2, etc. I must use a st

5条回答
  •  执念已碎
    2020-12-31 11:46

    Each instance of Data needs its own non-static member variable that stores its ID. A static variable can be used to store the last used ID which would be incremented in the constructor of Data.

    Instead of a static counter, which is not thread-safe, consider using boost's uuid:

    #include 
    #include 
    #include 
    #include 
    
    using boost::lexical_cast;
    using boost::uuids::uuid;
    using boost::uuids::random_generator;
    
    std::string id_ = lexical_cast((random_generator())());
    

提交回复
热议问题