C++指向临时变量的引用

C++ reference pointing to a temporary variable?

本文关键字:变量 引用 C++      更新时间:2023-10-16
class ClassB {
    int m_b;
public:
    ClassB(int b) : m_b(b) {}
    void PrintClassB() const {
        cout << "m_b: " << m_b << endl;
    }
};

int main(int argc, char* argv[])
{
    const ClassB &af = ClassB(1);
    af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
}

鉴于上面的代码,我很难理解这个片段:

Q1>这句话是什么意思?

const ClassB &af = ClassB(1);

以下是我的理解:

af refers to a temporary variable ClassB(1) and after the

执行此行,临时变量被销毁并 af 指未定义的变量。在此过程中,没有 调用复制构造函数。

那为什么我们还能发出以下声明并得到结果呢?

af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
const ClassB &af = ClassB(1);

const这里延长了正在创建的临时对象(即ClassB(1)(的生命周期。它的范围一直持续到af超出范围;

af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3

这是因为,af只不过是临时对象的引用,该引用是构造的,1传递给它的构造函数。

您所看到的是由标准保证的。

C++03 12.2 临时对象:

第二个上下文是当引用绑定到临时时。引用绑定到的临时或作为临时绑定的子对象的完整对象的临时在引用的生存期内持续存在,除非下面指定...

[示例:

class C {
    // ...
public:
    C();
    C(int);
    friend C operator+(const C&, const C&);
    ˜C();
};
C obj1;
const C& cr = C(16)+C(23);
C obj2;
..a third temporary T3 to hold the result of the addition of these two expressions. 
The temporary T3 is then bound to the reference cr..The temporary T3 bound to the
reference cr is destroyed at the end of cr’s lifetime, that is, at the end of the
program. 

—结束示例]

我认为你可以依靠Herb Sutter博客中的这个例子来帮助你理解参考文献,常量参考文献及其生命周期。http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/(

来自他的博客:

通常,临时对象仅持续到它出现的完整表达式的末尾。但是,C++特意指定将临时对象绑定到堆栈上的 const 引用可将临时对象的生存期延长到引用本身的生存期,从而避免了常见的悬空引用错误

不,你误解了行为,这是一个定义明确的行为。

临时绑定到 const

引用的生存期一直持续到 const 的生存期。

因此,从ClassB(1)临时返回的寿命因此延长到af的生命周期,即main的闭合支撑。