Rahul said:
Hi Everyone,
I have the following code,
class Test
{
public : Test()
{
}
};
int main()
{
Test object;
return(0);
}
If my understanding is correct, the constructor isn't responsible for
the allocation of the memory for the object, so how does the actual
memory allocation occur?
What exactly happens beneath the following statement,
Test object;
Thanks in advance!!!
'object' is said to have automatic storage duration.
int main ()
{
auto Test object;
}
A C++ compiler would generate the necessary processor instructions to
allocate storage from a pre-allocated memory area called the stack; a
memory area typically directly accessible to the processor. A C++
compiler would also generate the necessary processor instructions to
free the memory.
int main ()
// Instructions to allocate memory for 'object'.
{
Test object;
}
// Instructions to free memory for 'object'.
int main ()
// Instructions to allocate memory for 'object'.
{
Test object;
// Instructions to allocate memory for 'object2'.
{
Test object2;
}
// Instructions to free memory for 'object2'.
}
// Instructions to free memory for 'object'.
int main ()
// Instructions to allocate memory for 'object'.
{
Test object;
// Instructions to allocate memory for 'object2'.
{
Test object2;
// Instructions to allocate memory for 'object3'.
{
Test object3;
}
// Instructions to free memory for 'object3'.
}
// Instructions to free memory for 'object2'.
}
// Instructions to free memory for 'object'.
The constructor is then called to initialize the memory to a known
internal state/assumption.
Some people want to hide all the underlying pieces, but this is how it
most often will be implemented, to this date, I'm 99% sure. Although,
all you need to know at one level is that C++ deals with allocating and
freeing the memory (thus the name automatic storage duration). So once
object2 and object3 are out of scope, they no longer exist.
What's really going to bake your noodle later on is--what happens if
there's not enough memory? Some systems crash. Others deal with it in
one way or another. It's beyond the scope of C++. If you really care
about control, you would research this on each target system. Though,
statistically, how often would this occur?