C++ 返回值、引用、常量引用

标签 c++ reference const-reference return-by-reference return-by-value

你能解释一下返回值、引用值和 const 引用值的区别吗?

值(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引用好?

最佳答案

除非你写一些奇怪的东西,否则没有区别

(v1 += v2) = v3;

第一种情况,赋值给一个临时的,整体效果是v1 += v2

第二种情况,赋值给v1,所以整体效果是v1 = v3

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

Why returning of reference is better than returning of value?

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

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

你可以像上面的例子那样防止奇怪,同时仍然允许不那么奇怪的链接,比如

v1 = (v2 += v3);

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

关于C++ 返回值、引用、常量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21778045/

相关文章:

javascript - 如何删除或插入 Javascript 多维数组

c++ - C++引用变量

c++ - const 引用右值的类数据成员的生命周期是多少?

c++ - 带有常量参数的友元函数

C 或 C++ 中的 Java ByteArray 等价物

c++ - Qt5.3(mingw32)中删除QQuickView的内存管理问题

c# - 命名空间 'SQLite' 中不存在类型或命名空间名称 'System.Data'(是否缺少程序集引用?)

c++ - const auto& 用于存储函数结果,值得吗?

c++ - Link Error : xxx is already defined in *****.LIB::究竟是什么错误?

c++ - 一段代码不能被intel编译器编译但是clang会编译它