I am trying to do a simple class to unique ID conversion. I am thinking about adding a static method:
class A {
static int const *GetId() {
static int const id;
return &id;
}
};
Each class would then be identified by unique int const *
. Is this guaranteed to work? Will the returned pointer really be unique? Is there any better simpler solution?
I have also thought about pointer to std::type_info
:
class A {
static std::type_info const *GetId() {
return &typeid(A);
}
};
Is that better?
Edit:
I don't need to use the id for serialization. I only want to identify a small set of base classes and I want all subclasses of some class to have the same id
An address is a non-negative integer. Each time a program is run the variables may or may not be located in same memory locations. Each time you run the program above may or may not result in the same output.
The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).
Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading.
Yes, this will work. Each static
local will be given distinct memory location at the time when the module is loaded and it will persist until the module is unloaded. Remember, static
locals are stored in static storage that is distributed during compilation and they persist till the module gets unloaded, so they will have distinct memory locations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With