Static counter in C ++

I am trying to create a Data class whose objects contain a unique identifier.

I want the 1st identifier of the object to be 1, the second to 2, etc. I should use static int , but all objects have the same identifier, not 1, 2, 3 ...

This is the Data class:

 class Data { private: static int ID; public: Data(){ ID++; } }; 

How can I do this so that the first ID is 1, the second is 2, etc.?

+6
source share
5 answers

It:

 class Data { private: static int ID; const int currentID; public: Data() : currentID(ID++){ } }; 

Besides a static counter, you also need an element associated with the instance.

+14
source

If the identifier is static, then it will have the same value for all instances of the class.

If you want each instance to have consistent id values, you could combine a static attribute with a class variable, for example:

 class Data { private: static int ID; int thisId; public: Data(){ thisId = ++ID; } }; int Data::ID = 0; 

If the application is multithreaded, you will have to synchronize it with something like a pthread mutex.

+9
source

Each instance of Data needs its own non-static member variable, which retains its identifier. A static variable can be used to store the last identifier used, which will be incremented in the Data constructor.

Instead of a static counter that is not thread safe, consider using boost uuid :

 #include <boost/lexical_cast.hpp> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_generators.hpp> #include <boost/uuid/uuid_io.hpp> using boost::lexical_cast; using boost::uuids::uuid; using boost::uuids::random_generator; std::string id_ = lexical_cast<std::string>((random_generator())()); 
+1
source

Initialization of the static variable inside the function is allowed, so the solution may be something like this

  class Data { private: static int ID () { static int ID = 0; return ID ++; } int myId; public: Data(): myId (ID ()) { } }; 
+1
source

where is the instance (not static) here? you need to declare a new instance id field like this

 int m_ID; 

then in your constructor do

 Data(){m_ID = ::InterlockedIncrement(&ID);} 

in a blocked or other thread safe way

-1
source

Source: https://habr.com/ru/post/917363/


All Articles