当作用域消失时,我们如何通过引用 return 变量

How can we return a variable by reference while the scope has gone as

当 returning 函数的范围已经消失并且它的 vars 在 returning var 时被销毁时,我们如何通过引用 return 变量?

如果我们按照以下方式避免这种情况:

int fr = 9;
int& foo() {
    //const int& k = 5;
    return fr;
};

我会问我们是否必须将 returned 变量声明为全局变量?

可以return函数局部static变量而不是全局变量,当然:

int& foo() {
    static int rc = 9;
    return rc;
}

但是请注意,您仍然有效地拥有一个具有所有问题的全局变量,例如,来自多个线程的潜在并发访问。至少,从 C++11 开始,函数局部 static 变量的初始化是线程安全的:函数局部 static 变量在声明语句的第一次执行时被初始化。

使用 static 关键字,使其作用域贯穿整个代码。 示例:-

  int& fun(){
  static int a =5;
  return a;
  }

 int main()
 {
  int &b=fun();
  cout<<b;
 }

您可以创建一个class并介绍一个成员,您return作为参考。这将比 'static function member' 解决方案更透明,但需要更多开销,因此只有在您需要 class 时才合理。

class Foo {
public:
   Foo() ;
   int& getFoo() {return myFoo;} 
private:
   int myFoo;
};

注意:OP 和其他答案建议对 return 预先存在的对象进行变体(全局,static 函数,成员变量)。然而,这个答案讨论了 returning 一个生命周期从函数开始的变量,我认为这是问题的精神,即:

how can we return a variable by reference while the scope of the returning function has gone and its vars have been destroyed as soon as returning the var.

通过引用新对象 return 的唯一方法是动态分配它:

int& foo() {
    return *(new int);
}

然后,稍后:

delete &myref;

现在,当然,那是不是通常的做事方式,也不是人们看到函数时所期望的return作为参考。在 Deleting a reference.

查看所有注意事项

不过,如果对象是 "commits suicide" later by calling delete this. Again, this is not typical C++ either. More information about that at Is delete this allowed?.

相反,当你想 return 一个在函数内部构造的对象时,你通常做的是:

  • Return 按值(可能利用 copy elision)。
  • Return 动态分配的对象(return 指向它的原始指针或 class 包装它,例如智能指针)。

但这两种方法都return通过引用实际对象。

我假设这是一个研究原则的学术示例,因为编码它的明显方法是 return 按值。

考虑到这个先决条件,这看起来像是智能指针的用例。您可以将变量包装在智能指针中,并按值 return 包装。这类似于@Acorns 的回答,但是变量一旦不再被引用就会自行删除,因此不需要显式删除。