C ++返回值,引用,常量引用 [英] C++ Return value, reference, const reference

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

问题描述

您能告诉我返回值,引用值和const引用值之间的区别吗?

Can you explain to me the difference between returning value, reference to value, and const reference to value?

值:

Vector2D operator += (const Vector2D& vector)
{
    this->x += vector.x;
    this->y += vector.y;
    return *this;
}

非常量引用:

Vector2D& operator += (const Vector2D& vector)
{
    this->x += vector.x;
    this->y += vector.y;
    return *this;
}

常量参考:

const Vector2D& operator += (const Vector2D& vector)
{
    this->x += vector.x;
    this->y += vector.y;
    return *this;
}

这有什么好处?我想知道const引用传递给函数背后的含义,因为您要确保不要修改指向函数内部引用的该值.但是我对返回const reference的含义感到困惑.为什么返回引用比返回值更好,为什么返回const引用比返回非const更好?

What is the benefit of this? I understand the sense behind const reference passing to function as you want to make sure not to modify this value on which reference is pointing to inside a the function. But I'm confused by the meaning of returning const reference. Why returning of reference is better than returning of value, and why returning of const reference is better than returning of not-const reference?

推荐答案

除非您写类似的东西,否则没有区别

There is no difference unless you write something weird like

(v1 += v2) = v3;

在第一种情况下,分配将是临时的,而总体效果将是v1 += v2.

In the first case, the assignment will be to a temporary, and the overall effect will be v1 += v2.

在第二种情况下,分配将分配给v1,因此总体效果将是v1 = v3.

In the second case, the assignment will be to v1, so the overall effect will be v1 = v3.

在第三种情况下,将不允许分配.这可能是最好的选择,因为这种怪异几乎可以肯定是一个错误.

In the third case, the assignment won't be allowed. This is probably the best option, since such weirdness is almost certainly a mistake.

为什么返回引用比返回值更好?

Why returning of reference is better than returning of value?

这可能更有效:您不必复制对象.

It's potentially more efficient: you don't have to make a copy of the object.

为什么返回const引用要比返回非const引用更好?

and why returning of const reference is better than returning of not-const reference?

您可以像上面的示例一样防止怪异,同时仍然允许更少的怪异链接,例如

You prevent weirdness like the above example, while still allowing less weird chaining such as

v1 = (v2 += v3);

但是,正如评论中所指出的,这意味着您的类型不支持某些人认为与内置类型相同的(ab)use形式.

But, as noted in the comments, it means that your type doesn't support the same forms of (ab)use as the built-in types, which some people consider desirable.

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

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