gpt4 book ai didi

c++ - 对带有运算符重载的移动语义感到困惑

转载 作者:太空宇宙 更新时间:2023-11-04 11:42:02 27 4
gpt4 key购买 nike

当与运算符重载一起使用时,我对 C++ 移动语义感到困惑。

例如:(标题)

#pragma once
#include <vector>
namespace Mat {
using namespace std;
template <class T = double>
class Matrix {
public:
vector<vector<T>> &data;
size_t Rows;
size_t Cols;
// ctor
Matrix(size_t rows = 1, size_t cols = 1) :
data(*(new vector<vector<T>>(rows, vector<T>(cols)))) {
Rows = rows;
Cols = cols;
}
// copy assignment
Matrix &operator=(const Matrix &m) {
cout << "Copy =" << endl;
delete &data;
Rows = m.Rows;
Cols = m.Cols;
data = *(new vector<vector<T>>(m.data));
return *this;
}
// move assignment
Matrix &operator=(Matrix &&m) {
cout << "Move =" << endl;
Rows = m.Rows;
Cols = m.Cols;
data = m.data;
return *this;
}
// destructor
~Matrix() {
delete &data;
}
// addition
Matrix &operator+(const Matrix &right) {
const auto &left = *this;
auto &result = *(new Matrix<T>(left.Rows, left.Cols));
for (size_t r = 0; r < Rows; r++) {
for (size_t c = 0; c < Cols; c++) {
result.data[r][c] = left.data[r][c] + right.data[r][c];
}
}
return result;
}
};
}

(主要/驱动程序)

int _tmain(int argc, _TCHAR* argv []) {
Mat::Matrix<double> mat1(3,3);
Mat::Matrix<double> mat2(3, 3);
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1, 6);
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
mat1.data[r][c] = distribution(generator);
mat2.data[r][c] = distribution(generator);
}
}
Mat::Matrix<double> mat3;
mat3 = mat1 + mat2;
}

当我执行这段代码时。它表明“mat3 = mat1 + mat2”正在使用复制赋值运算符。我期望(并希望)它使用移动赋值运算符。我正在使用 VS2013。

有人可以解释为什么会发生这种情况以及我如何获得所需的移动语义吗?谢谢

最佳答案

您的 operator+ 不仅会泄漏内存,还会返回 Mat::Matrix 通过引用。因此表达式 mat1 + mat2 只能绑定(bind)到:

Matrix &operator=(const Matrix&);

您要做的是按值返回一个 Matrix。最后,我看到您到处都在使用 new。您不需要动态分配,尤其是对于 std::vector

关于c++ - 对带有运算符重载的移动语义感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21035580/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com