C++将结构的所有权转移给函数

Emi*_*mil 2 c++ optimization

是否可以将C++(或C++ 0x)中的局部变量的所有权转移给函数,在返回后将其保留为未定义,因此可以进行优化?

struct A {
    int a[100000];
};

int func(A& s){
    //s should now be "owned" by func and be undefined in the calling function
    s.a[2] += 4;
    return s.a[2];
}

int main(){
    A s;
    printf("%d\n", func(s));
    //s is now undefined
}
Run Code Online (Sandbox Code Playgroud)

我希望函数"func"被优化为简单地返回sa [2] +4,但不改变内存中的实际值,就像"s"是"func"中的局部变量一样.如果无法在标准C++中完成,是否可以在g ++中进行一些扩展?

Pup*_*ppy 5

不,这是不可能的,标准或扩展,这是因为没有优化值.编译器可以简单地证明在这种情况下不再有对局部变量的引用.失败了所有其他事情,你可以通过这样做来琐碎地模仿这种效果

int main() {
    {
        A s;
        printf("%d\n", func(s));
    }
}
Run Code Online (Sandbox Code Playgroud)

能够做那种事情将是非常危险的,没有任何好处.