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

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

问题描述

你能解释一下返回值、引用值和常量引用值之间的区别吗?

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 引用的含义感到困惑.为什么返回引用比返回值好,为什么返回const引用比返回not-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.

为什么返回常量引用比返回非常量引用更好?

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) 使用形式,有些人认为这是可取的.

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天全站免登陆