"new" keyword

1
2
3
  class X {};
  
  X* obj = new X() 


Question:- 1) is this object created at compile time or run time.
2) if it is run time, what compiler does that helps in creating object in heap
3) if object is created at compile time than how compiler handle below code

1
2
3
4
5
6
7
8
int i;
X* data[10]
std::cin>>i; //suppose user input is 10 at run time

for(i;i>=0;i--)
{
   data[i] = new X();
}
is this object created at compile time or run time.
run time

what compiler does that helps in creating object in heap
pardon?
I meant that

when compiler sees line

X* obj = new X()

how it handle this, as the obj is in stack and pointer returns by new X() refers to heap memory. So how compiler bind location from heap to obj which is on stack. compiler should provide some kind of support to get above binding

The 'obj' is a variable in stack. Its type is "a pointer to object of type X". The size of a pointer variable is quite simple, so there is no challenge in allocating enough memory for it from stack when the function is called. The value stored by a pointer variable is a memory address, essentially an unsigned integer. Storing an integer in stack variable should be no great feat, right?

If it is a miraculous achievement, then so is int a; a = 42; too.

In the original example you do have a static array, again allocated from stack. It is big enough to store 10 memory addresses. No different from single pointer.
Hi Keskiverto,

in int a; a = 42; memory allocation is on stack and at compile time itself we know it.

But in case of new, heap memory location is stored in a variable that is in stack(obj).

there must be some copying mechanism that know the location of both pointer returned by new and obj that receive the pointer value from heap.

stack and heap are in the same memory. hence pointer wise there's no difference between them.

the difference between stack and heap is only how it's organized (i.e. how the memory is allocated and free'd)
Topic archived. No new replies allowed.