返回的对象分配给引用 [英] Returned object assigned to reference

查看:60
本文介绍了返回的对象分配给引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下事项:


#include< iostream>


struct X

{

int x;

X(){x = 6; }

};


X val()

{

返回X(); < br $>
}


int main()

{

X& x = val();

X x2 = x;

std :: cout<< x.x<< " " << x2.x;

}


调用val()返回的对象的生命周期是多少?我b / b
会认为它应该立即销毁,创建一个

悬空参考,但程序可以运行,返回的对象是

直到它的封闭范围结束了吗?

Consider the following:

#include <iostream>

struct X
{
int x;
X() { x = 6; }
};

X val()
{
return X();
}

int main()
{
X & x = val();
X x2 = x;
std::cout << x.x << " " << x2.x;
}

What is the lifetime of the object returned by the call to val()? I
would have thought it should be destroyed immediately, creating a
dangling reference, yet the program works, does the returned object
live until the end of it''s enclosing scope?

推荐答案

* Andrew Ward:
* Andrew Ward:
考虑以下内容:

#include< iostream>

struct X
{
int x;
X(){x = 6; }
};

X val()
{
返回X();
}

int main()
{X / amp; x = val();
X x2 = x;
std :: cout<< x.x<< " " << x2.x;
}

调用val()返回的对象的生命周期是多少?我原本认为它应该被立即销毁,创建一个悬挂引用,但程序可以工作,返回的对象是否存在直到它的封闭范围结束?
Consider the following:

#include <iostream>

struct X
{
int x;
X() { x = 6; }
};

X val()
{
return X();
}

int main()
{
X & x = val();
X x2 = x;
std::cout << x.x << " " << x2.x;
}

What is the lifetime of the object returned by the call to val()? I
would have thought it should be destroyed immediately, creating a
dangling reference, yet the program works, does the returned object
live until the end of it''s enclosing scope?




任何东西,因为这是未定义的行为。


对const的引用将是另一回事。

然后引用将在范围结束时有效。

-

答:因为它弄乱了人们通常阅读文本的顺序。

问:为什么这么糟糕?

A:热门发布。

问:什么是最烦人的事情usenet和电子邮件?



Anything, because this is Undefined Behavior.

A reference to const would be another matter.

Then the reference would be valid until the end of the scope.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?


你能解释一下你的意思吗?对const的引用将

是另一回事。 ;通过修改给出的例子。

Could you please explain what you mean by "A reference to const would
be another matter." by modifying the example given.


* Andrew Ward:
* Andrew Ward:
你能解释一下你的意思吗? const将是另一回事。通过修改给出的例子。
Could you please explain what you mean by "A reference to const would
be another matter." by modifying the example given.




请引用您所回复的内容;我不知道你到底在说什么。


-

答:因为它弄乱了人们通常阅读文字的顺序。

问:为什么这么糟糕?

A:热门帖子。

问:usenet和电子邮件中最烦人的是什么?



Please quote what you''re replying to; I don''t know what the heck you''re
talking about.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?


这篇关于返回的对象分配给引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆