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

q09*_*987 4 c++

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
}
Run Code Online (Sandbox Code Playgroud)

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

Q1>这条线是什么意思?

const ClassB &af = ClassB(1);
Run Code Online (Sandbox Code Playgroud)

这是我的理解:

af refers to a temporary variable ClassB(1) and after the
Run Code Online (Sandbox Code Playgroud)

执行此行,临时变量被销毁,af指的是未定义的变量.在此过程中,不会调用任何复制构造函数.

那为什么我们仍然可以发出以下声明并获得结果呢?

af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
Run Code Online (Sandbox Code Playgroud)

Mah*_*esh 5

const ClassB &af = ClassB(1);
Run Code Online (Sandbox Code Playgroud)

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

af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
Run Code Online (Sandbox Code Playgroud)

这是因为,af只是临时对象的引用被构造传递1给它的构造函数.

  • `const`本身没有做任何事情,但它与引用的绑定是延长生命周期的因素.碰巧它需要被const绑定.(但在C++ 0x中考虑你也可以做'ClassB && af =`.) (2认同)
  • @GMan:确切地说,要更清楚:**临时不能绑定到非const引用,但它可以绑定到const引用.** (2认同)

Eri*_*c Z 5

您看到的内容由标准保证.

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. 
Run Code Online (Sandbox Code Playgroud)

- 末端的例子]