gpt4 book ai didi

c++ - 带引用的 std::tuple 无法在 clang 中编译,但不能在 gcc 中编译

转载 作者:行者123 更新时间:2023-12-01 22:58:04 25 4
gpt4 key购买 nike

以下代码:

using input_t = std::tuple<short, int&, const long&, const double>;
int b = 1;
int c = 2;
input_t t{0, b, c, 3};

clang 9.0 中编译失败,但在 gcc 9.2 中编译成功:https://godbolt.org/z/6CuEaf

clang 将失败并出现以下错误:

In file included from <source>:2:

tuple:133:17: error: reference member '_M_head_impl' binds to a temporary object whose lifetime would be shorter than the lifetime of the constructed object

: _M_head_impl(std::forward<_UHead>(__h)) { }

^~~~~~~~~~~~~~~~~~~~~~~~~

/tuple:218:4: note: in instantiation of function template specialization 'std::_Head_base<2, const long &, false>::_Head_base<int &>' requested here

_Base(std::forward<_UHead>(__head)) { }

^

/tuple:217:4: note: in instantiation of function template specialization 'std::_Tuple_impl<2, const long &, const double>::_Tuple_impl<int &, int, void>' requested here

: _Inherited(std::forward<_UTail>(__tail)...),

^

/tuple:217:4: note: in instantiation of function template specialization 'std::_Tuple_impl<1, int &, const long &, const double>::_Tuple_impl<int &, int &, int, void>' requested here

/tuple:627:11: note: in instantiation of function template specialization 'std::_Tuple_impl<0, short, int &, const long &, const double>::_Tuple_impl<int, int &, int &, int, void>' requested here

: _Inherited(std::forward<_UElements>(__elements)...) { }

^

<source>:10:13: note: in instantiation of function template specialization 'std::tuple<short, int &, const long &, const double>::tuple<int, int &, int &, int, true>' requested here

input_t t{0, b, c, 3};

^

这里哪一个是正确的?我没有看到任何会导致超过 bc 生命周期的情况。

<小时/>

最佳答案

考虑以下代码:

struct X
{
X(int i)
{
std::cerr << "constructed from " << i << std::endl;
}
~X() { std::cerr << "destructed\n"; }
};

struct Y
{
const X& ref_;
Y(const X& ref) : ref_(ref)
{
std::cerr << &ref << std::endl;
}
};

int main ()
{
int i = 1;
Y y(i);
std::cerr << &y.ref_ << std::endl;
}

其输出如下:

constructed from 1
0x7fff6a0bb78b
destructed
0x7fff6a0bb78b

现场演示是 here .

它有点模拟std::tupleY这里。在 Y y(i) ,参数ref绑定(bind)到 X 类型的临时变量。但是这个临时值随着 ref 的生命周期而被破坏。参数结束。然后,ref_正如 @rafix07 在评论中指出的那样,成为悬空引用。

因此,以导致绑定(bind)到临时对象的方式初始化引用类型的元组成员是没有意义的。问题是编译器是否需要在这里发出诊断。我认为没有必要,而且我在 [tuple] 中没有看到任何相关信息。 .

它只是说,关于 forward_as_tuple :

Constructs a tuple of references to the arguments in t suitable for forwarding as arguments to a function. Because the result may contain references to temporary objects, a program shall ensure that the return value of this function does not outlive any of its arguments.

但是 tuple 的定义中没有出现相同的措辞(“直接”)构造函数。

关于c++ - 带引用的 std::tuple 无法在 clang 中编译,但不能在 gcc 中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58803178/

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