C++ Return value, reference, const reference(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++ 返回值、引用、常量引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 返回值、引用、常量引用


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 近似搜索的工作原理 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01