编译器会为这两个语句生成相同的代码吗?
foo1(int* val){(*val)++;}
foo2(int &val){val++;}
它会简单地将指针写入 foo 堆栈帧的参数部分吗?或者,在第二种情况下,调用者和 foo 的堆栈帧是否会以某种方式重叠,使得调用者的局部变量在堆栈上占用与 foo 的参数相同的内存?
编译器会为这两个语句生成相同的代码吗?
foo1(int* val){(*val)++;}
foo2(int &val){val++;}
它会简单地将指针写入 foo 堆栈帧的参数部分吗?或者,在第二种情况下,调用者和 foo 的堆栈帧是否会以某种方式重叠,使得调用者的局部变量在堆栈上占用与 foo 的参数相同的内存?
这两个调用应该生成完全相同的代码,除非你有某种奇怪的编译器。
这取决于。
如果在大多数平台上编译为库,则为两者生成的代码将是等效的,如果不完全相同的话。
任何好的编译器都会内联这样一个小函数,因此很有可能不是获取堆栈上某些东西的地址来递增指向的值,而是直接递增该值。任何内联函数的堆栈帧都嵌入在调用者的堆栈帧中,因此在这种情况下会重叠。
堆栈不能重叠。
考虑参数可能是全局的、堆对象,或者即使存储在堆栈中,它也可能不是最后一个元素。根据调用约定,其他元素可能放置在一个堆栈帧和传递给函数的参数(即返回地址)之间......
请注意,即使堆栈中没有添加任何内容,也无法在编译函数时做出决定,而是在编译器正在处理调用函数时做出决定。一旦函数被编译,它不会根据调用它的位置而改变。
关于堆栈帧的重叠,我在这里找到了以下信息 :
For some purposes, the stack frame of a subroutine and that of its caller can be considered to overlap, the overlap consisting of the area where the parameters are passed from the caller to the callee. In some environments, the caller pushes each argument onto the stack, thus extending its stack frame, then invokes the callee. In other environments, the caller has a preallocated area at the top of its stack frame to hold the arguments it supplies to other subroutines it calls. This area is sometimes termed the outgoing arguments area or callout area. Under this approach, the size of the area is calculated by the compiler to be the largest needed by any called subroutine.
So in your case if only variables in local scopes of caller functions are passed to foo2 overlapping thing may be possible!