c++ - 是否可以为 Matrix 类实现 move operator+/operator-/operator*?
问题描述
我正在考虑如何使用 Add(Subtract)和 Multiply 操作定义一类实矩阵 NxN。我正在寻找有效的内存使用。
class Matrix {
private:
std::size_t _size_n;
double **_pMatrix;
public:
Matrix(const size_t n);
~Matrix();
double &operator()(size_t, const size_t);
double operator()(size_t, const size_t) const;
size_t size_n() const { return _size_n; }
};
std::ostream &operator<<(std::ostream &, const Matrix &);
Matrix operator+(const Matrix&, const Matrix&);
Matrix operator-(const Matrix&, const Matrix&);
Matrix operator*(const Matrix&, const Matrix&);
解决方案
是的,你可以有额外的重载
Matrix/*&&*/ operator+(const Matrix&, Matrix&&);
Matrix/*&&*/ operator+(Matrix&&, const Matrix&);
Matrix/*&&*/ operator+(Matrix&&, Matrix&&);
重用临时内存之一。
它们都可以Matrix& operator += (Matrix&, const Matrix&)
通过更改顺序来实现,因为 + 是对称的。operator -
将需要专用代码。
另一种优化内存的方法是使用表达式模板而不是直接计算结果。
不过,它在生命周期问题(尤其是auto
)方面有其缺点。
推荐阅读
- java - 为什么我收到此错误?java.lang.ClassCastException: android.text.SpannableStringBuilder 不能转换为 java.lang.String
- c - 在线程之间共享动态分配的 char *
- html - Django 延迟加载图片
- c# - 如何使用图形资源管理器 SDK?
- kubernetes - k8s: configmap 安装在“..data”目录的符号链接中
- reactjs - 在 reactJS 中返回 undefined 的 Redcuers
- api-platform.com - API 平台 - 自定义子资源路径不起作用
- python - 连续读取文件并将新行添加到列表(python)
- elasticsearch - 匹配 ELK 中特定位置的子字符串电子邮件地址
- docker - 为什么在 azure pipline 上拉取基本图像需要很长时间?