Want to knwo when copy occur when move a struct that impl copy

have a example about copy and move.

when first assign p to q and pass q to function. the addresss change, but why the threee function call print the same address?

If you think about how function calls work, it makes perfect sense. The address of a local variable that's "on the stack" (I'll explain the quotes in a bit) is determined by the containing function's stack frame. The stack is a contiguous chunk of memory; if you call a function, then return, then call the exact same function, then there's no reason why the physical addresses should change. The new stack frame is allocated in the exact same place as the old one (namely, after the frame of the current, outer, calling function), overwriting the old one.

Anyway, due to how heavily and aggressively modern compilers optimize the code, none of the above actually has any meaning. Local variables may not live on the stack (they are promoted to registers and/or optimized away entirely when possible), and there's no guarantee around physical addresses changing or not changing across function calls. You can't observe the theoretical modus operandi by printing actual addresses on a physical machine.

2 Likes

i have the same guess at first. function call work at the same stack position. but when i insert some code between function call. address also keep the same.

Creating another Person in the stack frame of main won't do anything to change the behaviour you see. The stack frame is created once at the beginning of main and is not increased by allocations done at a point after calling receive. You can see the address being different if you increase the call stack by calling receive from another function. Example. You can see the creation of the stack frame at the beginning of each (non-inlined) function in godbolt. The rsp register (the stack pointer) is decreased at the beginning and increased at the end of the function call.

1 Like

quit awesome tool.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.