gpt4 book ai didi

c++ - 存储在类中的闭包中通过引用捕获的临时对象的生命周期

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:07 26 4
gpt4 key购买 nike

考虑以下代码片段:

struct foo { };

template <typename F>
struct impl : F
{
impl(F&& f) : F{std::move(f)} { }
auto get() { return (*this)(); }
};

template <typename X>
auto returner(X&& x)
{
return impl{[&x]{ return x; }};
// ^~
}

int main()
{
auto x = returner(foo{}).get();
}

live example on wandbox.org


  • 是否保证 foo{}returner(foo{}).get() 表达式的整个持续时间内都有效?

  • 或者 foo{} 是否只对 returner(foo{}) 有效,从而导致未定义的行为调用 impl::get()?


标准在 [class.temporary] 中说:

Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.

[intro.execution]

A full-expression is

  • an unevaluated operand,

  • a constant-expression,

  • an init-declarator or a mem-initializer, including the constituent expressions of the initializer,

  • an invocation of a destructor generated at the end of the lifetime of an object other than a temporary object ([class.temporary]), or

  • an expression that is not a subexpression of another expression and that is not otherwise part of a full-expression.

我不确定与 foo{} 相关的 full-expressionreturner(foo{}) 还是 returner(foo{}).get().

最佳答案

这里的重要部分是:

A full-expression is [...] an expression that is not a subexpression of another expression and that is not otherwise part of a full-expression.

所以在 returner(foo{}).get() 中,returner(foo{}) 是表达式 returner(foo{} ).get(),所以它不是一个完整的表达式。因此:

Is it guaranteed that foo{} will be alive for the entire duration of the returner(foo{}).get() expression?

是的。

关于c++ - 存储在类中的闭包中通过引用捕获的临时对象的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48052568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com