c++ - operator+= 可以调用自身但 "*this"与 "rhs"交换吗?

标签 c++ operator-overloading

编辑:我想我会在响应之前添加这个......这是一个类的分配的一部分所以我必须坚持底层数组并且我必须坚持重载运算符,没有那些花哨的模板化爵士乐东西(无论如何我都不会理解)。

EDIT2:我本质上想接听电话“A + B”,但在我的函数中将其反转为“B + A”

我的目标是尽量减少新内存分配的数量,因此我想尽可能避免在以下方法中调用复制构造函数(“if”情况):

Poly& Poly::operator+=(const Poly& rhs) {
    // actual addition of rhs to *this
    if (maxExponent < rhs.maxExponent) {
        Poly temp(rhs);

        for (int i = 0; i <= maxExponent; i++) {
            temp.polynomial[i] += polynomial[i];
        }

        *this = temp;
        //return *this;
    }
    else {
        for (int i = 0; i <= rhs.maxExponent; i++) {
            polynomial[i] += rhs.polynomial[i];
        }
    }

    return *this;
}

我以为我会成为一个聪明人并尝试这种偷偷摸摸的策略......但我无法获得正确的类型转换以使其正常工作(如果可能的话):

Poly& Poly::operator+=(const Poly& rhs) {
    // actual addition of rhs to *this
    if (maxExponent < rhs.maxExponent) {
        return (rhs + *this);
    }
    else {
        for (int i = 0; i <= rhs.maxExponent; i++) {
            polynomial[i] += rhs.polynomial[i];
        }
    }

    return *this;
}

我的想法是,基本上通过调用自身但切换参数的顺序,我可以直接使用 rhs,因为它不再是 const,我什至不必调整新数组的大小。这是我的 operator+ 供引用,因为它们一起工作:

inline Poly operator+(Poly lhs, const Poly& rhs)
{
    lhs += rhs;
    return lhs;
}

我正在尝试做的事情是否可行?

最佳答案

您在寻找:

template<typename T, typename U>
friend Poly operator+(T&& lhs, U&& rhs)
{
    if (lhs.maxExponent < rhs.maxExponent)
        return Poly(std::forward<U&&>(rhs)) += lhs;
    return Poly(std::forward<T&&>(lhs)) += rhs;
}

(由于是 friend,只有当参数是 Poly 时,它才会通过依赖于参数的查找找到。你可以用一些来扩充它enable_if.)

(你也可以在没有模板的情况下做到这一点......但是你最终会得到四个版本:lhsrhs 可以是 const Poly&Poly&& 并且有四种组合。对于其中一些组合,std::forward 没有好处,但也没有坏处。)

直接回答您的问题 -- 不,交换 lhs += rhslhsrhs 是个坏主意。 += 应该修改左侧的对象并保持右侧不变。这意味着您不能从 rhs 窃取资源(当然除非它是右值引用。)

operator+= 可以从 rhs 窃取资源的一种情况是当它是一个右值引用时,那么:

Poly& Poly::operator+=(Poly&& rhs)
{
    if (maxExponent < rhs.maxExponent)
        swap(rhs);

    for (int i = 0; i <= rhs.maxExponent; i++) {
        polynomial[i] += rhs.polynomial[i];
    }

    return *this;
}

关于c++ - operator+= 可以调用自身但 "*this"与 "rhs"交换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21150398/

相关文章:

c++ - 用于进程/任务调度的简单离散事件模拟库(C++)?

c++ - 如何将 Delphi 的 “array of string” 参数翻译成 C++?

c++ - 存储 2D 点以便快速检索矩形内的点

python - 重载 python 三元运算符

c++ - 当我只重载它以接受 Rational 类型的参数时,我的 Rational Number 类如何使用 += 和 long long 参数?

c++ - C++ 中的运算符重载(有和没有 friend )

c++ - C++ 中的矩阵与数组的数组及其动态分配

c++ - 这个 'else' 是如何工作的?

c++ - 为什么在全局命名空间中使用 << 运算符是一个坏主意?

c++ - 在 C++ 中重载运算符时,为什么 T* 优于 bool?