【发布时间】:2018-12-28 19:59:16
【问题描述】:
我刚开始使用 C++ 并被困在移动构造函数上。这是我的.cpp:
SimpleMatrix::SimpleMatrix(SimpleMatrix &&other_mat) {
cols = other_mat.cols;
rows = other_mat.rows;
data_ = other_mat.data_;
other_mat.cols = 0;
other_mat.rows = 0;
other_mat.data_ = nullptr; // <- Error here
}
我在other_mat.data_ = nullptr 收到了No viable overloaded = 错误。什么地方出了错?这是我初始化矩阵的方式吗?
这是.hpp文件中的相关部分:
class SimpleMatrix {
public:
SimpleMatrix(std::size_t nrows, std::size_t ncols);
SimpleMatrix(std::initializer_list<std::initializer_list<double>> data);
SimpleMatrix(SimpleMatrix&& other_mat);
SimpleMatrix& operator=(SimpleMatrix&& other_mat);
private:
std::vector<std::vector<double> > data_;
int rows, cols;
};
【问题讨论】:
-
由于您的所有类型都是 RAII 类型,因此您无需编写任何特殊的成员函数。编译器生成的将为您工作。另外,想想你在
other_mat.data_ = nullptr;中所做的事情。data是指针吗?如果不是,那么赋予它nullptr的值意味着什么? -
您也不需要
rows或cols。那里已知的向量有自己的大小,它们有一个.size()成员函数。 -
data_ = other_mat.data_;正在执行数据的复制。您没有在移动构造函数中进行移动构造,而是在进行复制构造,然后尝试清除前一个对象,这在性能方面并不相同。 -
“
.hpp文件中的相关部分”缺少一个非常“相关部分”:移动构造函数定义本身。 -
您对@Someprogrammerdude 的缺失部分是正确的。我已经编辑过了。 _非常感谢。
标签: c++ matrix rvalue-reference move-constructor nullptr