簡體   English   中英

C++ 模板拷貝構造函數

[英]C++ template copy constructor

模板類上的 C++ 模板復制構造函數中,我發現無法完成模板復制構造函數。 我嘗試這樣做並設法成功。 我認為這是因為類中包含移動構造函數。 當我評論移動構造函數時,它不會編譯: 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. 還有其他方法可以編寫模板復制構造函數嗎?

我認為,您定義了一個“構造函數”。 它不是“復制構造函數”。 以下錯誤是它的結果: - 如果您只聲明移動構造函數(沒有復制構造函數),則復制構造函數被“刪除”。 - 如果您定義了“任何構造函數”,那么編譯器會創建默認的復制構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM