【问题标题】:C++ template copy constructorC++ 模板复制构造函数
【发布时间】:2020-03-06 15:48:10
【问题描述】:

C++ template copy constructor on template class,我发现模板复制构造函数不能做。我尝试做到这一点并设法成功。我认为这是因为类中包含移动构造函数。当我评论移动构造函数时,它不会编译:error: use of deleted function 'matrix::Matrix<TYPE>::Matrix(const matrix::Matrix<TYPE>&) [with TYPE = double]。我在 Windows 10 上使用 MinGW(GCC 6.3.0)。

标题:

namespace matrix {
enum IDENTITY { BLANK, I_1, I_2, I_3, I_4};
template<class TYPE = double>
class Matrix {
public:
    Matrix(const Matrix& m) = delete;   //delete normal copy constructor
    template <class U> Matrix(const Matrix<U>& m);   //template copy constructor
    ~Matrix();

    Matrix(Matrix&& m) noexcept{   //move constructor
        std::cout << "Move constructor" << std::endl;
    }
    .
    .//Some other functions declaration
    .
private:
    unsigned int rows_ = 0;
    unsigned int cols_ = 0;
    TYPE *data_;
};
.
.//Member functions definition
.

主要:

int main(){
    matrix::Matrix<int> m2(matrix::I_4); //normal constructor, Identity matrix 4x4
    matrix::Matrix<double> m1 = m2;   //copy constructor, error here if without move constructor
    m1(0,1) = 2;   //assign m1(0,1) = 2
    //show matrix
    std::cout << m1;
    std::cout << m2;
}

结果:

 1     2     0     0
 0     1     0     0
 0     0     1     0
 0     0     0     1

 1     0     0     0
 0     1     0     0
 0     0     1     0
 0     0     0     1

Process returned 0 (0x0)   execution time : 0.062 s

问题是:

  1. 为什么移动构造函数使模板复制构造函数可行?
  2. 这样做有什么后果吗?这样做安全吗?
  3. 有没有其他写模板拷贝构造函数的方法?

【问题讨论】:

  • 我们可以得到minimal reproducible example 吗?您的代码的修改版本适用于复制出的移动构造函数:coliru.stacked-crooked.com/a/6dbc7966fd21627f
  • 如果您希望您的代码与 C++14(由 gcc6.3 使用)一起使用,请制作 matrix::Matrix&lt;double&gt; m1 {m2};
  • T 的复制构造函数是一个非模板,它采用T&amp;const T&amp; 类型的参数。任何其他构造函数都不是复制构造函数。
  • @NathanOliver 我在我的电脑上复制了你的代码,它给出了同样的错误。也许是因为编译器。
  • @rafix07 那工作。我尝试使用matrix::Matrix&lt;double&gt; m1 (m2),这也可以。好像matrix::Matrix&lt;double&gt; m1 = m2被区别对待了,你知道为什么吗?

标签: c++ templates copy-constructor move-constructor


【解决方案1】:

我认为,您定义了一个“构造函数”。而且它不是“复制构造函数”。 以下错误是它的结果: - 如果您仅声明移动构造函数(没有复制构造函数),则复制构造函数被“删除”。 - 如果您定义“任何构造函数”,则编译器会创建默认的复制构造函数。

【讨论】:

  • "如果你只声明了移动构造函数(没有拷贝构造函数),拷贝构造函数被“删除”了,你有这个源码吗?
猜你喜欢
  • 1970-01-01
  • 2015-12-08
  • 2011-05-24
  • 1970-01-01
  • 2016-09-12
  • 2016-03-22
  • 2011-07-15
  • 1970-01-01
相关资源
最近更新 更多