Home > Blockchain >  How to generate an automatic and sequential class ID?
How to generate an automatic and sequential class ID?

Time:10-25

I would like to generate an automatic ID attached to every instantiation of a class, respecting the order of appearance of the instantiation statements in the source code. I found this: How to generate auto id in c ?

At the end of that example it looks like the ID produced by incrementing a static variable is unique and also sequential:

Id id1;        // id1.get_id() will return 1
Id id2;        // id2.get_id() will return 2
Id id3;        // id3.get_id() will return 3

I can understand the IDs are unique, but can I be sure they are also sequential? Couldn't be, for instance, I get something like:

Id id1;        // id1.get_id() will return 2
Id id2;        // id2.get_id() will return 1
Id id3;        // id3.get_id() will return 3

...because who knows in which order the compiler is going to do the instantiations?

Is that ok, or is there a safe way to get the desired result?

Best regards

CodePudding user response:

can I be sure they are also sequential?

Yes. The initialisation of id1 is sequenced before the initialisation of id2, similarly id2 and id3.

CodePudding user response:

It is a safe way to get the desired results as long as you're not working with threads. A single-threaded program will always execute in the order you tell it to... so if you declare "MyClass A, B, C;" you'll always get A=0 B=1 C=2 whereas if you declared: "MyClass A, C, B;" you'd get A=0, B=2, C=1

if you don't know what threads are you are most likely working on a single-threaded program so rest assured it is safe!

  • Related