C ++ 11:基于范围的语句:“range-init”一生? [英] C++11: The range-based for statement: "range-init" lifetime?

查看:138
本文介绍了C ++ 11:基于范围的语句:“range-init”一生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最新的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())
...

该行变为:

 自动&& r = boo(); 
...

因此boo()的临时返回值在结束语句auto& r = boo(),然后r是循环入口处的挂起引用。 ??这个推理是否正确?

解决方案


这个推理是否正确?


$ b blockquote>

因此boo()的临时返回值在语句auto& r = boo()结束时被销毁[...]


将临时对象绑定到引用会将其生命周期延长到引用的生命周期。所以临时的持续整个循环(这也是为什么在整个结构周围有一个额外的 {} 集合:正确地限制临时的生命周期)。

这是根据C ++标准的§12.2第5段:


第二个上下文是当引用绑定到临时时。
引用绑定的临时变量或临时变量
引用绑定的子对象的完整对象
在引用的生存期内保持不变:



[此处不适用的各种异常]


这是一个有趣的属性,允许滥用非范围内的事件的范围循环: http://ideone.com/QAXNf


In the latest C++ standard it implies that:

for (foo : bar)
    baz;

is equivilant to:

{
    auto && r = bar;
    for ( auto it = r.begin(), end = r.end(); it != end; ++it )
    {
        foo = *it;
        baz;
    }
}

When bar in the above is a function call that returns a collection, eg:

vector<string> boo();

ie

for (auto bo : boo())
    ...

Doesn't the line become:

auto&& r = boo();
...

And so the temporary return value of boo() is destroyed at the end of the statement "auto&&r=boo()", and then r is a hanging reference at the entry of the loop. ?? Is this reasoning correct? If not, why not?

解决方案

Is this reasoning correct? If not, why not?

It is correct up until this point:

And so the temporary return value of boo() is destroyed at the end of the statement "auto&&r=boo()" [...]

Binding a temporary to a reference extends its lifetime to be that of the reference. So the temporary lasts for the whole loop (that's also why there is an extra set of {} around the whole construct: to correctly limit the lifetime of that temporary).

This is according to paragraph 5 of §12.2 of the C++ standard:

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:

[various exceptions that don't apply here]

This is an interesting property that allows abusing the ranged-for loop for non-rangey things: http://ideone.com/QAXNf

这篇关于C ++ 11:基于范围的语句:“range-init”一生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆