简体   繁体   English

C ++临时变量生命周期

[英]C++ temporary variable lifetime

Is this code valid? 这段代码有效吗?

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

    // Do something silly...

    return 42;
}

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) . 出于某种原因,我认为临时的std::vector对象(从赋值符号右侧应该在构造之后被破坏(从而使引用无效)

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. 然而,调试证明我错了,而且,我意识到我不太明白为什么在函数返回时会破坏临时变量


I guess I have a strong misunderstanding of something fundamental, so please enlighten me :) 我想我对一些基本的东西有很强的误解,所以请赐教:)

The code you've shown is illegal – temporaries can only bind to rvalue references or const lvalue references. 您显示的代码是非法的 - 临时代码只能绑定到右值引用或const左值引用。

VC++ happens to allow it as an extension (and gives a level 4 warning saying so). VC ++碰巧允许它作为扩展(并提供4级警告说明)。

The normal lifetime of a temporary is until the end of the full expression in which it is created; 临时的正常生命周期直到创建它的完整表达式结束; it's not necessarily destructed immediately on use. 它不一定在使用时立即被破坏。 If the temporary is used to initialize a reference, it's lifetime is extended to match that of the reference (with the notable exception of a temporary created in the initializer list of a constructor). 如果临时用于初始化引用,则延长其生命周期以匹配引用的生命周期(具有在构造函数的初始化程序列表中创建的临时的明显例外)。

Of course, your code is illegal; 当然,你的代码是非法的; if the reference is to a non-const, it can only be initialized with some sort of an lvalue. 如果引用是非const,则只能使用某种左值初始化。 But if it were legal (and at least one compiler accepts it), the lifetime should be extended to match that of the reference. 但如果它是合法的(并且至少有一个编译器接受它),则应该延长生命周期以匹配引用的生命周期。

You have a reference to a deallocated object. 您有一个对已释放对象的引用。 It works by 'sheer luck' (see The C++ Programming Language , section 10.4.10 Temporary Objects). 它的工作原理是“纯粹的运气”(参见C ++编程语言 ,第10.4.10节临时对象)。 You can't guarantee that it'll work in every compiler. 你无法保证它在每个编译器中都能正常工作。

You can only be certain that the lifetime of the temporary is extended if it's bound to a const reference. 您只能确定临时的生命周期是否已扩展,如果它绑定到const引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM