I am trying to understand the new operator more closely. I do understand the fact that it allocated memory from the heap and returns a pointer to the memory. My question is that once I get the pointer and use it to store another pointer to another declared variable, how does the value copy or the value pointed to by happen? So for instance
i declare a variable
int x = 4;
and say
int* ptr = new int;
ptr = &x;
ptr points a chunk of memory from the heap. x is defined in a stack owning a separate chunk of memory. ptr and the address of x are the same. If I delete ptr, x is still valid as it still exists in the memory. When I say *ptr, I am looking for the value pointed to by ptr, which in this case is 4. My question is that 4, where does that reside. Does it live in two separate chunks of memory. One is represented by x and other I just got from new. How does the process happen? How does 4 get transmitted across the two chunks, or I am missing sthg? Please help.
Also when I say ptr = &x, is that a bitwise copy. In other words, do I forever loose the memory I just got access to through the heap?
No, it doesn’t. After the assignment, it points at the address of variable
x, which has automatic storage. You have lost the handle to the dynamically allocatedintinitially pointed at byptr, so you can no longer delete it.4does not get transmitted across any “chunks” of memory. When you de-reference,ptr, you get the variable referred to by x, which holds the value4.Try this example: