I have been reading about how memory is allocated in C++.
A few resources to mention:
http://www.geeksforgeeks.org/memory-layout-of-c-program/
http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory
Object creation on the stack/heap?
Global memory management in C++ in stack or heap?
http://msdn.microsoft.com/en-us/library/vstudio/dd293645.aspx
Heap / Stack and multiple processes
Do different programs gets their memory from a common heap or from a separate heap?
http://computer.howstuffworks.com/c28.htm
I want to clarify a few points based on my reading:
According to http://www.geeksforgeeks.org/memory-layout-of-c-program/ Section 4 Stack "Stack, where automatic variables are stored, along with information that is saved each time a function is called"
Suppose:
class myClass{
int a;
char b;
public:
myClass(int a,char b)
{
this->a = a;
this->b = b;
}
};
1)According to what I have read, when we compile this code the binary sits in program memory and nothing has been allocated on stack yet. Correct?
Now in my main:
int main()
{
myClass Ob(1,'c');
return 0;
}
2) Now an object Ob of size 5 bytes (4 bytes (int), 1 byte (char) - 32 bit OS) is created on stack, since it is an automatic variable. Correct ?
3) When the constructor myClass(int a,char b)
is called do the temporary variables (parameters a, b) are created on stack for constructor and then destroyed after creating the object Ob? Like when we call a function by passing parameters by value.
Now suppose another class
class pointerClass {
int a;
char* b;
public:
pointerClass(int size){
b= new char[size];
a=size;
}
};
Now in main :
int main()
{
pointerClass ptr(10) ; //Step 1
}
4) Does this mean ptr object of size 8 bytes ( int a (4 bytes) , char* b (4 bytes i.e. this is just holding an address pointing to heap ) is created on stack ? Further a memory of 10 bytes (corresponding to new char[10] is allocated on heap) which is being pointed by the content of char* b? Am I correct?
5)When we pass a parameter to a function by reference such as fn (int *a,char* b)
or fn(int& a,char& b)
does this mean that a temporary pointer/reference is created on stack for the function which points to the actual object being passed and destroyed when the function returns? or rather the actual object is passed instead of creating and destroying a temporary pointer/reference on stack for the function?
This I asked yesterday but I am not satisfied with the answer: Constructor, Copy Constructor and Stack Creation : C++
6)When we overload a fn such as fn(int a,char b)
fn(int& a,char& b)
we can call from main as fn(A,B)
with below cast
static_cast<void(*)(int, char)>(fn)(a, c); //Calls fn(int a,char b)
static_cast<void(*)(int&, char&)>(fn)(a, c);//Calls fn(int& a.char& b)
What exactly is happening here ? What is void (*) .
Thanks