Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are non-static member of a static object allocated?

Tags:

c++

object

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

like image 252
Pierre Avatar asked Apr 16 '15 08:04

Pierre


People also ask

How memory is allocated for static members and non-static members?

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.

Where non-static members are stored in Java?

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.

Where are the non-static variables are stored in the memory?

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.

Where are static variables allocated?

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.


1 Answers

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?

like image 183
Erik Alapää Avatar answered Sep 28 '22 16:09

Erik Alapää