[英]how to implement movable overloads without violating the DRY principle in C++?
While implementing method and operator overloading in some of my classes to leverage the rvalue references in C++, often I write some code with poor design violating the DRY Principle. 在我的某些类中实现方法和运算符重载以利用C ++中的右值引用时,我经常会编写一些设计欠佳的代码,这违反了DRY原理。 What would be a better alternative for the code snippet below?
对于下面的代码片段,哪种方法更好? (This code is just to illustrate the problem)
(此代码仅用于说明问题)
class matrix_2_2
{
int _m[2][2];
public:
matrix_2_2 operator*(const matrix_2_2& m) const &
{
matrix_2_2 res;
for(int i = 0 ; i < 2 ; i ++)
for(int j = 0 ; j < 2 ; j++)
for(int k = 0 ; k < 2 ; k++)
res._m[i][j] = (res._m[i][j] + _m[i][k]*m._m[k][j]);
return res;
}
matrix_2_2 operator*(matrix_2_2&& m) &&
{
matrix_2_2 res;
for(int i = 0 ; i < 2 ; i ++)
for(int j = 0 ; j < 2 ; j++)
for(int k = 0 ; k < 2 ; k++)
res._m[i][j] = (res._m[i][j] + _m[i][k]*m._m[k][j]);
return move(res);
}
This code presents a lot of repetition in the implementations details, I would like to encapsulate the logic and reuse it in different overloads, without losing the movable advantage because of rvalue to lvalue implicity conversions. 这段代码在实现细节上有很多重复,我想封装逻辑并在不同的重载中重用它,而又不会因为从右值到左值的隐式转换而失去可移动的优势。
A better alternative would be to just delete the rvalue-qualified operator*
completely and have just the one operator*
, this one: 更好的选择是完全删除右值限定的
operator*
,而只删除一个operator*
,即:
matrix_2_2 operator*(const matrix_2_2& m) const;
Your class is a POD - there is no difference between a move and a copy in this case, so there is no possible advantage for you to gain by taking advantage of move semantics. 您的类是一个POD-在这种情况下,移动和复制之间没有区别,因此,利用移动语义无法获得任何好处。 You're gaining in code complexity, but not in performance.
您正在获得代码复杂性,而不是性能。 There really is no logical difference for what your code should do if
this
is &
or &&
... 真的是你的代码应该怎么做,如果没有逻辑区别
this
是&
或者&&
...
Also, this: 另外,这:
matrix_2_2 operator*(matrix_2_2&& m) &&
{
matrix_2_2 res;
...
return std::move(res);
}
is not the correct way to write that, as the last move
makes it impossible to do the named return value optimization, so you're doing an extra move
for code like: 这不是正确的写法,因为最后
move
使命名返回值优化变得不可能,因此您需要对以下代码进行额外的move
:
matrix_2_2 product = some_matrix() * some_other_matrix();
Rather than simply constructing res
in-place in product
. 而不是简单地在
product
中就地构建res
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.