编辑:我想我会在响应之前添加这个......这是一个类的分配的一部分所以我必须坚持底层数组并且我必须坚持重载运算符,没有那些花哨的模板化爵士乐东西(无论如何我都不会理解)。
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
.)
(你也可以在没有模板的情况下做到这一点......但是你最终会得到四个版本:lhs
和 rhs
可以是 const Poly&
或 Poly&&
并且有四种组合。对于其中一些组合,std::forward
没有好处,但也没有坏处。)
直接回答您的问题 -- 不,交换 lhs += rhs
的 lhs
和 rhs
是个坏主意。 +=
应该修改左侧的对象并保持右侧不变。这意味着您不能从 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/