【发布时间】:2013-02-28 07:59:17
【问题描述】:
我正在阅读 Eckel 的固定章节,并在解释 Temporaries 的部分混淆了。我能得到的是,当我们将引用传递给函数时,编译器会创建一个临时对象,它是一个 const 对象,因此即使我们将引用传递为
,我们也无法修改它f(int &a){}
现在我尝试在网上查看其他一些临时人员的参考资料,结果卡住了
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fcplr382.htm 和
Are all temporaries rvalues in C++?
这促使我认为临时对象不仅仅是在函数内部传递引用和为其创建 const 对象。现在我可以从这两个链接中得到一些东西,但不能说我已经理解临时对象的工作、功能和使用所有的。如果有人可以解释临时人员的概念,那将非常有帮助。在此先感谢。
bruce eckel 的原始示例是:
// Result cannot be used as an lvalue
class X {
int i;
public:
X(int ii = 0);
void modify();
};
X::X(int ii) { i = ii; }
void X::modify() { i++; }
X f5() {
return X();
}
const X f6() {
return X();
}
void f7(X& x) { // Pass by non-const reference
x.modify();
}
int main() {
f5() = X(1); // OK -- non-const return value
f5().modify(); // OK
// Causes compile-time errors:
//! f7(f5());
//! f6() = X(1);
//! f6().modify();
//! f7(f6());
} ///:~
【问题讨论】:
-
引用和临时没有直接关系。它与对象的创建/销毁方式有关。也许你最好重新开始..