Sometimes, I see that there is a mix of concepts between the duration of the storage and where does this occur. That is because sometimes I've seen the following statement:
int i; // This is in the stack!
int* j = new int; // This is in the heap!
But is this really true 100% of the time? Does C++ ensure where the storage takes place? Or, is it decided by the compiler?
Is the location of the storage independent from the duration?
For example, taking those two snippets:
void something()
{
int i;
std::cout << "i is " << i << std::endl;
}
vs:
void something()
{
int* i = new int;
std::cout << "i is " << i << std::endl;
delete i;
}
Both are more or less equivalent regarding the lifetime of i
, which is created at the begining and deleted at the end of the block, here the compiler could just use the stack (I don't know!), and the opposite could happen too:
void something()
{
int n[100000000]; // Man this is big
}
vs:
void something()
{
int* n = new int[100000000];
delete n;
}
Those two cases should be in the heap to avoid stack-overflow (Or at least is what I've been told so far...), does the compiler that also that into account, besides the storage duration?