简体   繁体   English

临时生命周期扩展和隐式转换为 const 引用

[英]Temporary lifetime extension and implicit conversion to a const reference

Normally, binding a temporary to a local const& extends the lifetime of the temporary until the end of the scope of the reference:通常,将临时对象绑定到本地const&延长临时对象的生命周期,直到引用范围结束:

struct Foo { void DoSomething() const; };
Foo Make();

const Foo& foo = Make(); // compiles
foo.DoSomething(); // ok, lifetime of foo was extended

But when an implicit conversion is involved, this is no longer the case:但是当涉及隐式转换时,情况就不再如此:

struct Foo { void DoSomething(); };
struct Bar { operator const Foo&() const; };
Bar Make();

const Foo& foo = Make(); // compiles calling the implicit conversion operator
foo.DoSomething(); // not ok, temporary Bar has been destroyed

Is this actually what is specified in the C++ standard?这实际上是 C++ 标准中指定的内容吗? Is this intended?这是故意的吗? Is it legal to declare such an implicit conversion operators to a const& ?将这种隐式转换运算符声明为const&是否合法? (Another question is how that conversion operator should be implemented. In this case, it would need to involve a reinterpret_cast relying on Foo and Bar having a compatible binary representation, which is probably undefined behavior. In C++20, probably a bit_cast might be used? But suppose Foo derived from Bar , a static_cast could be used, removing the undefined behavior and the situation does not change). (另一个问题是应该如何实现该转换运算符。在这种情况下,它需要涉及依赖于具有兼容二进制表示的FooBarreinterpret_cast ,这可能是未定义的行为。在 C++20 中,可能是bit_cast被使用?但是假设Foo派生自Bar ,可以使用static_cast ,删除未定义的行为并且情况不会改变)。

Is this intended?这是故意的吗?

Yes.是的。 The lifetime of temporary Bar won't be extended to the lifetime of foo .临时Bar生命周期不会延长到foo的生命周期。

In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference to which the temporary was bound, does not affect its lifetime.通常,不能通过“传递”来进一步延长临时文件的生命周期:从临时文件绑定的引用初始化的第二个引用不会影响其生命周期。

That means, the lifetime of temporary bound to reference directly would be extended.这意味着,直接绑定到引用的临时生命周期将被延长。 In this case, the temporary Bar returned by Make() isn't bound to foo directly.在这种情况下, Make()返回的临时Bar不直接绑定到foo

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

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