2012-08-03 23 views
2

考慮下面的代碼:是在此代碼中創建的臨時值?

class B; 

class A 
{ 
    public: 
    A() {} 
    A(B &b); 
}; 

class B {}; 

A::A(B &b) {} 

int main() 
{ 
    B b; 

    const A &refa = b;// does this line create a temporary value? 

    return 0; 
} 

我的問題是:該代碼const A &refa = b;創建一個臨時的價值或沒有?

回答

8

是的,臨時對象A(b)在初始化語句中創建,並立即綁定到常量引用refa。這具有延長臨時使用期限以符合refa變量範圍的作用。

+0

在什麼情況下,「const TYPE&」會創建一個臨時對象? – 2012-08-03 09:19:33

+0

考慮:int i; int const&refi = i;不會創建一個臨時對象,這是怎麼回事? – 2012-08-03 09:26:47

+1

@hu wang您可以通過將一些printf放入A :: A(B&b) – 2012-08-03 09:30:55