Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of a static variable

Tags:

c++

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

like image 465
Juraj Blaho Avatar asked Sep 23 '11 08:09

Juraj Blaho


People also ask

What is the address of a variable?

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.

Where are static variables located?

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).

How do you refer to a static variable?

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.

What is an example of a static variable?

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.


1 Answers

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.

like image 81
sharptooth Avatar answered Oct 15 '22 22:10

sharptooth