2017-02-17 59 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

相关问题