gpt4 book ai didi

c++ - 结构化绑定(bind)中的 const 引用是否会延长分解对象的生命周期?

转载 作者:IT老高 更新时间:2023-10-28 12:51:50 30 4
gpt4 key购买 nike

const auto& [a, b] = f(); 是否保证延长从 f() 返回的对象的生命周期,或者至少是对象 ab 是绑定(bind)的吗?通读the proposal我没有在语言中看到任何明显的东西来确保它确实如此,除非它只是被其他东西所覆盖。但是,以下内容不会延长临时的生命周期,所以我看不出它会如何被覆盖:

const auto& a = std::get<0>(f());

在论文的顶部,它似乎暗示它已被覆盖

the cv-qualifiers and ref-qualifier of the decomposition declaration are applied to the reference introduced for the initializer, not for the individual member aliases

但在实际标准的建议措辞中,我看到的最接近的提及如下,虽然我不确定如何阅读它以获得我正在寻找的保证:

if e is an unparenthesized id-expression naming an lvalue or reference introduced from the identifier-list of a decomposition declaration, decltype(e) is the referenced type as given in the specification of the decomposition declaration

gcc 和 clang 似乎都根据 wandbox experiment 将返回的对象的生命周期延长到作用域结束。 .一个 uglier one为我自己的类型实现所有的花里胡哨似乎可以延长外部对象及其其他数据成员的生命周期。

尽管几乎可以肯定作者的意图,但我想确定该语言保证这是安全的。

最佳答案

是的。诀窍是要意识到,尽管外观如此,[ 之前的结构化绑定(bind)声明部分并不适用于 identifier-list 中的名称。它们改为应用于声明隐式引入的变量。 [dcl.struct.bind]/1 :

First, a variable with a unique name e is introduced. If the assignment-expression in the initializer has array type A and no ref-qualifier is present, e has type cv A and each element is copy-initialized or direct-initialized from the corresponding element of the assignment-expression as specified by the form of the initializer. Otherwise, e is defined as-if by

attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt e initializer ;

where the declaration is never interpreted as a function declaration and the parts of the declaration other than the declarator-id are taken from the corresponding structured binding declaration.

然后将名称定义为 e 元素的别名或绑定(bind)到在 e 上调用 get 的结果的引用。

在您的示例中,就好像(假设 f 返回一个二元素 std::tuple):

const auto& e = f(); // 1
using E = remove_reference_t<decltype((e))>;
std::tuple_element<0, E>::type& a = get<0>(e);
std::tuple_element<1, E>::type& b = get<1>(e);

(除了 decltype(a)decltype(b) 得到特殊处理以隐藏它们的引用性。)

很明显,第 1 行确实延长了 f 的返回值的生命周期。

关于c++ - 结构化绑定(bind)中的 const 引用是否会延长分解对象的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41176231/

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