2

我想知道编译器是否有可能做到这些场景?

首先我们将 SomeDataType 定义为:

struct SomeDataType{
public:
int a;
int b;
int c;
};

场景 #1 _关于具有如下引用参数的被调用函数:

void doSomething(SomeDataType & input){
...
}

假设函数不是内联的,并且只有调用函数范围内的变量在程序中传递给该函数,并且考虑到引用不一定是指针这一事实,放置输入参数的内存部分在堆栈帧之间共享任何调用者函数和“doSomething”被调用者函数的堆栈帧,以便“doSomething”可以像寻址其本地范围内的任何局部变量一样寻址该参数,即通过将偏移量添加到确定其堆栈起始地址的基指针框架。

情景#2 _这对我来说似乎更不可能,但无论如何;关于返回“SomeDataType”类型结构的被调用函数:

SomeDataType doSomething(){
SomeDataType someStruct;
...
return someStruct;
};

结构“someStruct”所在的内存部分在任何调用者的堆栈帧和“doSomething”被调用函数的堆栈帧之间共享,因此请考虑调用函数中的以下语句:

SomeDataType TheStruct=doSomething();

在该调用者的范围内使用“TheStruct”会导致使用与被调用者范围内的“SomeStruct”所在的内存相同的部分,这意味着被调用者函数不会在任何地方复制“someStruct”,即使复制是必要的,比如在那里是调用者函数中的如下语句,表明目标不是调用者范围内的结构:

*pntrToSomewhere=doSomething();

将共享部分的内容复制到该指针指示的位置将是调用者的职责。

4

1 回答 1

0

If you pass a reference (or pointer) to a local variable in the calling function (caller), then that will be on the caller stackframe. Note that I'm not aware of any architecture, where if you lift the carpet and look at how it's actually working under the pretty surface, references aren't actually pointers. The standard doesn't REQUIRE that, but it is how it is implemented for at least most architectures - I'd actually be interested in understanding HOW ELSE you could implement it - but I haven't spent much time thinking about it.

The typical behaviour of a function that has a struct or class return type is that it passes an "extra" argument pointing to a temporary space to store the return type, e.g.:

 T myfunc(int x, int y)

 ...

 void foo()
 {
    ...
    T x = myfunc(2, 18);
    ...
 }

will appear the same as (the hidden argument won't necessarily be the FIRST argument - but it's almost certainly either first or last):

 void myfunc(T& hidden, int x, int y)

 void foo()
 {
    ...
    T x;
    myfunc(x, 2, 18);
    ...
 }

It is not really that the stackframe is shared, as much as "we pass pointers that are in the stackframe of the or another, earlier, caller.

So, yes, there can be accesses from the current callee into an earlier callers stackframe, for sure.

于 2013-06-27T09:12:22.437 回答