C ++临时变量生命周期 [英] C++ temporary variable lifetime

查看:175
本文介绍了C ++临时变量生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码是否有效?

int foo()
{
    std::vector<std::string>& v = std::vector<std::string>(5, "X");

    // Do something silly...

    return 42;
}



由于某种原因,我认为临时 std: : 应该在构造之后立即被破坏(因此使引用无效)。

For some reason I thought that the temporary std::vector object (right from the assignment sign) should be destructed right after it's construction (thus rendering the reference invalid).

但是,调试证明我错了,我意识到我不太明白为什么临时变量在函数返回时被破坏。 strong>

However, debugging proves that I'm wrong and, well, I realized that I don't quite understand why does the temporary variable is destructed when the function returns.

我想我对某些基本要素有很强的误解,所以请赐教: em>

I guess I have a strong misunderstanding of something fundamental, so please enlighten me :)

推荐答案

您显示的代码是非法的–临时只能绑定到右值引用或 const 左值引用。

The code you've shown is illegal – temporaries can only bind to rvalue references or const lvalue references.

VC ++恰好允许它作为一个扩展http://msdn.microsoft.com/en-us/library/186yxbac.aspx\"> a level 4 warning that so)。

VC++ happens to allow it as an extension (and gives a level 4 warning saying so).

这篇关于C ++临时变量生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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