【问题标题】:"No viable overloaded =" nullptr“没有可行的重载=”nullptr
【发布时间】: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 的值意味着什么?
  • 您也不需要rowscols。那里已知的向量有自己的大小,它们有一个.size() 成员函数。
  • data_ = other_mat.data_; 正在执行数据的复制。您没有在移动构造函数中进行移动构造,而是在进行复制构造,然后尝试清除前一个对象,这在性能方面并不相同。
  • .hpp 文件中的相关部分”缺少一个非常“相关部分”:移动构造函数定义本身。
  • 您对@Someprogrammerdude 的缺失部分是正确的。我已经编辑过了。 _非常感谢。

标签: c++ matrix rvalue-reference move-constructor nullptr


【解决方案1】:

data_是一个向量非指针对象nullptr是将一个指针初始化为空指针。

您不能将非指针变量分配为空指针。而且 C++ 没有任何空值或对象的概念。

如果你想正确初始化向量,我建议你添加一个构造函数初始化列表:

SimpleMatrix::SimpleMatrix(SimpleMatrix &&other_mat)
    : data_(std::move(other_mat.data_))  // Move the data from the other vector
    , rows(other_mat.rows)
    , cols(other_mat.cols)
{
    // Clear the other matrix rows and cols
    other_mat.rows = 0;
    other_mat.cols = 0;
}

或者,您可以依赖 the rule of zero 并让编译器生成的构造函数为您处理所有事情,在这种情况下它应该可以正常工作:

class SimpleMatrix {
 public:
  SimpleMatrix(SimpleMatrix &&) = default;
  // ...
};

【讨论】:

  • 嗯,不完全正确:移出的对象将有一个空向量以及非零的rowscols 变量。要在不丢失编译器辅助的移动构造函数生成的情况下将它们归零,可以使用私有基类:rextester.com/SURN53114
  • 这解决了我的问题。但更重要的是,感谢您提供清晰且内容丰富的答案
猜你喜欢
  • 1970-01-01
  • 2020-10-16
  • 1970-01-01
  • 2014-07-30
  • 2021-11-05
  • 1970-01-01
  • 2018-08-26
  • 2015-06-26
  • 1970-01-01
相关资源
最近更新 更多