在C++中,通过引用扩展范围是否安全?

Bri*_*ndy 9 c++ scope reference

在C++中,通过引用扩展范围是否安全?

在代码中,我的意思是:

MyCLass& function badIdea()
{
    MyClass obj1;
    ...
    return obj1;
}
Run Code Online (Sandbox Code Playgroud)

Har*_*ich 21

通过引用扩展范围是不安全的.当obj1超出范围时,C++中的对象不被引用计数它将被删除,引用badIdea()的结果只会让你遇到麻烦


Mot*_*tti 15

可以使用引用扩展范围的唯一地方是const引用in namespace或函数范围(不包括类成员).

const int & cir = 1+1; // OK to use cir = 2 after this line 
Run Code Online (Sandbox Code Playgroud)

这个技巧在Andrei Alexandrescu的非常酷的范围防守中使用,以捕获const对具体范围防守的基类的引用.