2017-02-17 83 views
1

所以我有這樣的代碼:爲什麼有一個複製構造函數會導致此代碼中斷?

template<class T> 
struct IntegerType 
{ 
    T value; 

    //Next line causes errors 
    //constexpr IntegerType(IntegerType& value) : value(value.value) { } 
    constexpr IntegerType(T value) : value(value) { } 
}; 
template<class int_t> 
class FullMult{ 
    int_t value; 
    int_t carry; 
    public: 

    constexpr FullMult() : value(0), carry(0) { } 
    constexpr FullMult(const int_t& value, const int_t& carry) : value(value), carry(carry) { } 

}; 

int main() 
{ 
    FullMult<IntegerType<unsigned int> > thing 
     = FullMult<IntegerType<unsigned int> >(
      IntegerType<unsigned int>(12),IntegerType<unsigned int>(12)); 
} 

但是當我嘗試通過取消註釋行constexpr IntegerType(IntegerType& value) : value(value.value) { }代碼休息,以一個拷貝構造函數添加到類型IntegerType並告訴我,我想使用的拷貝構造FullMult類型:

use of deleted function 'FullMult<IntegerType<unsigned int> >::FullMult(FullMult<IntegerType<unsigned int> >&&)' 

這是給我的錯誤代碼:

template<class T> 
struct IntegerType 
{ 
    T value; 

    //Next line causes errors 
    constexpr IntegerType(IntegerType& value) : value(value.value) { } 
    constexpr IntegerType(T value) : value(value) { } 
}; 
template<class int_t> 
class FullMult{ 
    int_t value; 
    int_t carry; 
    public: 

    constexpr FullMult() : value(0), carry(0) { } 
    constexpr FullMult(const int_t& value, const int_t& carry) : value(value), carry(carry) { } 

}; 

int main() 
{ 
    FullMult<IntegerType<unsigned int> > thing 
     = FullMult<IntegerType<unsigned int> >(
      IntegerType<unsigned int>(12),IntegerType<unsigned int>(12)); 
} 

這裏發生了什麼事?

+0

您是否使用一個類作爲另一個類的模板參數? – Kupto

+2

問題中的代碼應該是破碎的代碼,而不是工作代碼。請清楚明確地發佈一個顯示問題的MCVE –

+0

@Kupto是..... – DarthRubik

回答

4

一個問題就行:

constexpr FullMult(const int_t& value, const int_t& carry) : value(value), carry(carry) 

你跟const int_t類型的參數初始化類成員int_t value;。但是沒有匹配的構造函數。 IntegerType拷貝構造函數接受非const引用,並且不能綁定到const int_t

但是,即使您單獨修復此行,還有第二個問題,即出現在錯誤消息中的問題。碼(縮寫爲清楚起見):

F thing = F(...bla...); 

調用的F布展構造函數。或者至少,即使操作被取消,它也會執行復制/移動合格檢查。但是如錯誤信息所示,F(F&&)被刪除。這是因爲默認情況下的定義是:

F(F&& other): value(std::move(other.value)), carry(std::move(other.carry)) {} 

IntegerType沒有匹配的構造函數 - 拷貝構造函數以非const左值引用不綁定到x值std::move(other.value)


這兩個問題都可以通過使IntegerType複製構造函數接受const引用來解決。

或者,第二個問題可以通過除複製構造函數之外給IntegerType移動構造函數來解決。 (但第一個問題仍然存在)。

+0

NB。通過鏈接提供的gb或clang在godbolt上,我得到了一堆表明問題的診斷信息。 –

+0

你打敗了我......要從我未完成的答案中使用一勺,請嘗試:'constexpr IntegerType(const IntegerType&value):value(value.value){} – Kupto

相關問題