【发布时间】:2012-03-11 18:33:26
【问题描述】:
在最新的 C++ 标准中,它暗示:
for (foo : bar)
baz;
等价于:
{
auto && r = bar;
for ( auto it = r.begin(), end = r.end(); it != end; ++it )
{
foo = *it;
baz;
}
}
当上面的bar是一个返回集合的函数调用时,例如:
vector<string> boo();
即
for (auto bo : boo())
...
这条线不就变成了:
auto&& r = boo();
...
于是 boo() 的临时返回值在语句“auto&&r=boo()”的末尾被销毁,然后 r 是循环入口处的挂起引用。 ??这个推理正确吗?如果没有,为什么不呢?
【问题讨论】:
-
首先,
vector<string> boo();没有声明对象。它声明了一个函数。其次,我不明白你的问题。 -
Yes "vector
boo()" 是返回集合的示例函数的签名。然后在下面的行中调用该函数。