延长 std::tuple<int&,int> 的生命周期,方法是将其分配给 const std::tuple<int, int>&
Extending lifetime of std::tuple<int&,int> by assigning it to const std::tuple<int, int>&
我正在使用std::tuple
类,发现一些我会说是相当意外的行为。
考虑代码:
#include <iostream>
#include <tuple>
int i = 20;
std::tuple<int&, int> f() {
return std::tuple<int&, int>(i, 0);
}
int main() {
const std::tuple<int, int>& t = f();
int j = ++i;
std::cout << std::get<0>(t) << "n";
}
这似乎可以在所有主要编译器上编译和打印20
。由于两种类型不同,此标准是否符合或未定义的行为?我知道可以通过将其分配给const T&
来延长临时的使用寿命,但据我所知std::tuple<int&, int>
与std::tuple<int, int>
的类型不同。
这是定义良好的行为。
const std::tuple<int, int>& t = f();
没有为您提供对您在f()
中创建的元组的引用,因为它们具有不同的类型。 相反,发生的事情是从f()
的回归中创建一个临时std::tuple<int, int>
,然后这个临时的必然会t
。 由于这是一个副本,因此您可以在该时间点获得i
的值,并且不再与之耦合。
你用过吗
const std::tuple<int&, int>& t = f();
然后21
将被打印出来,因为您仍然可以引用元组中的i
。
这不是
UB。
但据我所知
std::tuple<int&, int>
与std::tuple<int, int>
不是同一类型.
是的,引用不能直接绑定到不同类型的对象。给定const std::tuple<int, int>& t = f();
,返回的std::tuple<int&, int>
将被隐式转换为std::tuple<int, int>
,这是一个临时std::tuple<int, int>
。然后临时绑定t
,并将生存期延长至t
的生存期。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- int(c) 和 c-'0' 之间的区别。C++
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 是否可以从int转换为enum类类型
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 'short int'持有的值溢出,但"自动"不会溢出?
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 调用'begin(int [n])'没有匹配函数
- 没有显式声明的int[]中的foreach
- 在c++中访问int到类对象的映射时出错
- 为什么我无法更改"set<set>"循环中的值<int>
- EASTL矢量<向量<int>>连续的
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- 'structstd::对<int,int>'没有名为'push_back'