【发布时间】:2010-12-07 00:03:56
【问题描述】:
是否可以更改临时对象并将其作为参数传递?
struct Foo {
Foo& ref() { return *this; }
Foo& operator--() { /*do something*/; return *this; }
// another members
};
Foo getfoo() { return Foo(); } // return Foo() for example or something else
void func_val(Foo x) {}
void func_ref(const Foo & x) {}
int main() {
func_val(--getfoo()); // #1 OK?
func_ref(getfoo()); // #2 OK?
func_ref(getfoo().ref()); // #3 OK?
// the following line is a real example
// using --vector.end() instead of --getfoo()
func_ref(--getfoo()); // #4 OK?
const Foo & xref = --getfoo(); // Does const extend the lifetime ?
func_ref(xref); // #5 OK?
func_val(xref); // #6 OK?
}
众所周知,将临时对象分配给 const 引用会延长该临时对象的生命周期。那么我的代码的#4 和#5 行呢? 引用 x 在函数 func_ref 中是否始终有效是真的吗? 问题是 operator-- 返回了一些引用,编译器看不到这个引用和我们创建的临时值之间的任何关系。
【问题讨论】:
-
您能否详细说明代码的目标?作为一个抽象问题很有趣,但有时最好的答案可能不在您选择的路线上。
-
请详细信息
std::for_each(vector.begin(), --vector.end(), Functor());或const Iter & endminus = --vector.end(); std::for_each(vector.begin(), endminus, Functor());
标签: c++ reference temporary const-reference