Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 具有绑定到引用的临时子表达式的临时表达式的生存期_C++_Rvalue Reference_Object Lifetime_Temporary Objects - Fatal编程技术网

C++ 具有绑定到引用的临时子表达式的临时表达式的生存期

C++ 具有绑定到引用的临时子表达式的临时表达式的生存期,c++,rvalue-reference,object-lifetime,temporary-objects,C++,Rvalue Reference,Object Lifetime,Temporary Objects,在main中使用p是否安全?我相信绑定由mk_pair生成的临时对象会将其生存期延长到p,但是由Wrap{1}和Wrap{2}创建的临时对象呢 struct Wrap { int &&x; }; struct Pair { Wrap &&w1, &&w2; }; Pair mk_pair(Wrap &&w1, Wrap &&w2) { return Pair{std::move(w1),std::move(w2)

main
中使用
p
是否安全?我相信绑定由
mk_pair
生成的临时对象会将其生存期延长到
p
,但是由
Wrap{1}
Wrap{2}
创建的临时对象呢

struct Wrap { int &&x; };

struct Pair { Wrap &&w1, &&w2; };

Pair mk_pair(Wrap &&w1, Wrap &&w2) { return Pair{std::move(w1),std::move(w2)}; }

int main(int argc, char *argv[])
{
  Pair &&p = mk_pair(Wrap{1},Wrap{2});
  std::cout << p.w1.x << ' ' << p.w2.x << '\n';
  return 0;
}
struct Wrap{int&&x;};
结构对{Wrap&&w1,&&w2;};
对mk_对(Wrap&&w1,Wrap&&w2){返回对{std::move(w1),std::move(w2)};}
int main(int argc,char*argv[])
{
Pair&&p=mk_对(Wrap{1},Wrap{2});

std::coutNo.
Wrap{1}
Wrap{2}
未绑定到
main
中的自动引用,因此它们在行尾被销毁


mk\u对
返回的
的生存期已延长到
p
的生存期,但其引用是悬空的。

这是未定义的行为。在

mk_pair(Wrap &&w1, Wrap &&w2)
w1
w2
作为右值引用,这样可以延长函数的生命。然后返回一个引用这些引用的对象。问题是,当表达式结束时,通过引用传递的临时值将被销毁。这意味着您知道有引用要过期对象,并使用这些对象是未定义的行为