I have this code and I wonder about memory allocation.
void f(){
static A a;
//Other things...
}
class A {
public:
A();
private:
AnotherObjectType anotherObject;
};
where will the anotherObject
be allocated ? in the static
code segment or elsewhere ? is there a risk for anotherObject
to be overwritten ? (f
will be called several times).
Static variables reduce the memory footprint of the program. This is because the memory is allocated only once for a static variable during the time of class loading, while for a non-static variable, memory is allocated every time an instance of the class is created.
Non-static components are stored inside the object memory. Each object will have their own copy of non-static components. But, static components are common to all objects of that class.
Whereas, non-static methods and variables were stored in the heap memory. After the java 8 version, static variables are stored in the heap memory.
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 non-heap objects will be in the static segment, inside the static A instance of f().
Concerning overwriting, this could happen in older C/C++ if you used various singleton idioms in multi-threaded code. But e.g. newer gcc versions use the new standard requirements for automatic thread-safe initialization of static objects. See e.g. Is local static variable initialization thread-safe in C++11?
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