Form the link below Difference between Definition and Declaration says that:
Definition of a variable says where the variable gets stored. i.e.,
memory for the variable is allocated during the definition of the
variable.
And to my knowledge, the declaration of class looks like :
class stu ;
And the definition of class looks like :
class stu{
public:
int x;
};
And so from information above , the memory allocation of this class should happen when I write the complete definition of class.However,
from this link says that :
Memory will be allocated when you create an instance of the class.
which means that the memory woudl be allocated at the moment I write
stu s;
So I would like to know the exact time that memory would allocate for thsi class, in the other word, it happens during compile time or run time?
In general: The memory holding the values for the members is allocated when they are used, which is - with some exceptions - at runtime. (assuming it is not optimized away by the compiler)
The forward declaration of a class is for the compiler to make the type known.
The definition describes the class:
its member functions are transformed into machine code. Those - depending on the target architecture - exist in a data section that is loaded into memory. So the member function takes up memory before any instance is created.
The compiler also stores some information about the memory layout, which is either part of the machine code or also exists somewhere in a data section.
This memory allocation is however about the description of the class, and not what is generally referred to when you talk about memory allocation for a type.
The memory holding the values for the members is allocated when they are used which is generally at runtime. Under certain circumstances, the values of an instance of a type can already be determined at compile-time, which might have the result that those also become part of the data section.
Related
I guess my question requires no minmal working example; it's possible a no-brainer and easy to describe.
Let's assume there is a class instance which stores some objects as members. Now one of the members grows during runtime. After creating the instance member1 consumed 10 bytes and member2 20 bytes. Then object1 is modificated somehow and needs now 15 bytes.
My question is if the address of (the first byte of) member1 is unchanged? Or can it potentially be possible that the first byte of member1 has now another address as before?
Are member variables allocated at the heap?
Thanks for your feedback!
Best
Now one of the members grows during runtime.
This scenario is not possible in C++. The size of an object (and the size of a type) is constant at runtime.
member1 has now another address as before?
No. The address of an object will never change through its entire lifetime.
I have a Class instance whose members are from an external library, I don't even know how they internally store the members.
The type of a member variable must be complete. That means that the type must have been defined. If it is defined, then its size and the internal members are known. You have probably included the definition of the type by including a header file. You can read that header to find out the definition.
So this is only possible using heap allocation, is it?
Not necessarily. For example, there could be a pre-allocated buffer that can contain objects up to some constant limit.
But typically yes, dynamic objects use dynamic storage. Based on the observation of increasing memory use, this seems to be the case.
Basically, I have not been able to find much information about this on the internet, but I understand that the basic class instantiation is:
-> operator new() -> allocates memory from somewhere
-> constructor -> assigns values to "data types"
Now, what I want to know is, how does C++ allocate methods/functions of the class rather than its members. According to my web research, this cannot happen in new() because it is only allocating raw memory, and as far as I have gotten, I have not quite been able to figure out how this could be done in the constructor with functions (rather than function pointers). Also, I assume that because of the existence of the keyword static, without this keyword, it is allocated as part of the parent class. How and where does this happen?
Also, if the functions are included in the memory of the class, does the function sizeof() give the size of just the class and its members, or does it also include the related functions?
While compiling the code compiler takes stores the addresses of the starting point of the functions in the raw code. This address can be relative the starting location of the program or an absolute memory address.
The point is when the function is called the(assuming that scope issues are taken care of) in the code, while compiling the compiler just insert a jump statement to the address where the code of the function is present. For returning to the same location, there is some other operations taking place.
So when you say space is allocated, it just the space occupied by bytecode of the function plus the entry in a table inn compiler which says this function is present at this address
This is pretty much the case with every programming language(which compiles) not only C++.
As for your other part: sizeof(type) returns size in bytes of the object representation of type which is basically an aggregation of size of its members(if we leave out the padding which is done by compiler for optimization).
I am not sure how appropriate is this question, but -
I am curious about how the compiler sets memory aside for an object (allocation of memory) even before it is constructed (before even the constructor is called!).
How does it happen for primitive datatypes?
This sounds a bit naive, but what exactly is it ?
Is it entirely a run time process, or does it (the compiler) have any plans like to do this, to do that, during run-time, which it decides before hand during the compile- time. I have no idea at all!
An object, be it a primitive type, a pointer, or a instance of a big class, occupies a certain known amount of memory. That memory must somehow be set aside for the object. In some circumstances, that set-aside memory is initialized. That initialization is what constructors do. They do not set aside (or allocate) the memory needed to store the object. That step is performed before the constructor is called.
In other words, when does the memory allocation for literally ANY kind of variable happen, in terms of time, at which point? At which step in compilation (or run-time)?
Memory allocation always happens at run time. Memory reservation, for objects that reside on the stack, or for static variables, happens at compile time (or at run time for C99 VLAs).
Memory for an object's members is always in place before the constructor runs. It is the job of the compiler and its runtime support to ensure that is so.
Allocation objects created with new or new[] or some variant is done at runtime, by accessing the freestore and finding enough space to place the new object, prior to the constructor running.
Allocation for local objects within a function are done at runtime. However, this is usually accomplished by moving a stack pointer the correct size of bytes, and the space between the previous value and the new value is now reserved for the object. The constructors are run after the space is run.
Allocation for global and static objects are done at compile time by the compiler, and their constructors are run when the translation unit they are defined in is loaded (usually before main() begins executing).
Allocation for objects contained directly (not via pointer) within another object is done as part of the allocation for that object.
There's (loosely speaking) three typical scenarios: allocation on the stack, allocation from heap, and static allocation.
The first is what happens whenever you declare a local variable within a function:
void foo ( )
{
int bar = 42;
}
Here, the memory for bar is allocated on the stack. It is allocated at the time foo is called.
The second scenario happens when you create a class instance with the new operator:
void foo ( )
{
MyClass* bar = new MyClass( );
}
Here, the memory for i is allocated on the heap. This again happens at runtime, and occurs as the new operator executes. It works essentially in the same manner a C's malloc, if you're more familiar with that.
Finally, there's static allocation.
void foo ( )
{
static int bar = 42;
}
Here, the compiler knows ahead of time that memory will be needed for bar, and so it inserts into the executable an instruction telling the executable loader to reserve space, or literally makes a space in the executable for the variable to reside in. The memory for bar is therefore typically still allocated at runtime, as the executable loads.
It's been bothering me for a while but I didn't find any good resource about this matter. I have some global variables in my code. It's obvious that they are initialized in some order but is the memmory needed for all those objects reserved before any initialization take place?
here is the simple example of what might go wrong in my code and how I can use the answer:
I had a map<RTTI, object*> objectPool which holds samples of every class in my code, which i used to load objects from a file. To create those samples I use some global variables just to introduce class instance to objectPool. But sometimes those sample instances were initialized before ObjectPool itself. And that generated runtime error.
To fix that error I used some delayed initializer map<RTTI,object*>* lateInitializedObjectPool;. Now every instance first check if the objectPool is initialized and initilize it if not and then intoduce itself to the object pool. It seems to work fine but I'm worried if even the memmory needed for object pool pointer is not reserved before other classes begin to introduce themselves and that may cause access violation.
Variables declared at namespace scope (as opposed to in classes or functions) have the space for the objects themselves (sizeof(ObjectType)) allocated by the executable (or DLL) loader. If the object is a POD that uses aggregate initialization, then it typically gets its values set by having the linker write those values directly into the executable and the exe's loader simply blasting all of those into memory. Objects that don't use aggregate initialization get their values zeroed out initially.
After all of that, if any of these objects have constructors, then those constructors are executed before main is run. Thus, if any of those constructors dynamically allocate memory, that is when they do it. After the executable is loaded, but before main is run.
There's usually separate memory areas for variables that the compiler:
worked out initially contain all 0s - perhaps with a pre-main() constructor running to change their content
predetermined have a specific non-0 value, such that they can be written in a pre-constructed form into the executable image and page faulted in ready for use.
When I say a "separate memory area", I mean some memory the OS executable loader arranges for the process, just as per the stack or heap, but different in that these areas are of fixed pre-determined size. In UNIX, the all-0 memory region mentioned above is commonly known as the "BSS", the non-0 initialised area as "data" - see http://en.wikipedia.org/wiki/Data_segment for details.
C++ has the notion of "static storage duration". This refers to all kinds of variables that will take up a fixed amount of space during the execution of a program. These include not just globals, but also static variables at namespace, class and function level.
Note that the memory allocation in all cases can be done before main, but that the actual initialization differs. Also, some of them are zero-initialized before they're normally initialized. Precisely how all this happens is unspecified: the compiler may add a hidden function call, or the OS just happens to zero the process space anyway, etc.
Whcih occupies memory, a class or an object? And, is that at compile or execution time?
Thanks.
During compilation, the layout of memory is an implementation detail--you don't need to know or care.
During runtime, however... in C++, classes define types but (unless you activate RTTI which allows limited introspection into classes) don't generally occupy any memory themselves1--they're just the frameworks for the construction and destruction of objects. Their methods, however--the constructors, destructors, instance methods, and class methods, occupy some portion of executable memory, but compilers can and do optimize away any such methods that are not used in the program.
Instances of types (that is, objects as well as primitives like int variables) occupy the bulk of memory in C++, but for their member functions they refer back to their classes. Exactly how much memory an instance of a particular class uses is entirely and utterly an implementation detail, and you should generally not need to care about it.
1 Even then, the classes themselves don't use the memory, but their associated std::typeinfo instance does. But again, this is generally implementation-y stuff and not the sort of thing even wizened programmers pay much attention to.
The object instance is the one which occupies memory at execution time since a class is the blueprint of the object.
Also, in C++ there are static variables, local variables and global variables which also occupies memory.
Static, local and global variables are stored in BBS data segment, while objects are stored either in heap or in stack.
Objects are the instances of class, while class definition is used by compiler to create an object by it's class description. Class is like an instruction of "how to build table by yourself" that occupies only the paper it's written on, while an object is the real table made by yourself according to the instruction, that occupies the real space.