c – 竞争隐式和模板复制构造函数
发布时间:2020-12-16 09:41:08 所属栏目:百科 来源:网络整理
导读:关于 this帖子,请解释一下这种行为: #include stdio.hstruct B { B(B) { } B() { } };struct A { templatetypename T A(T){ printf("A(T)n"); } A() { }// B b; // when this is uncommented,output changes int i;};int main() { A a; A b(a);// B b; com
关于
this帖子,请解释一下这种行为:
#include <stdio.h> struct B { B(B&) { } B() { } }; struct A { template<typename T> A(T&){ printf("A(T&)n"); } A() { } // B b; // when this is uncommented,output changes int i; }; int main() { A a; A b(a); // B b; commented: // template wins: // A<A>(A&) -- specialization // A(A const&); -- implicit copy constructor // (prefer less qualification) // B b; uncommented: // implicit copy constructor wins: // A<A>(A&) -- specialization // A(A&); -- implicit copy constructor // (prefer non-template) printf("nAn"); A const a1; A b1(a1); // B b; commented: // implicit copy constructor wins: // A(A const&) -- specialization // A(A const&) -- implicit copy constructor // (prefer non-template) // B b; uncommented: // template wins: // A(A const&) -- specialization // (implicit copy constructor not viable) } B b时输出变化;没有注释. 显然,当B b时,隐式拷贝构造函数从A(A const&)变为A(A&);没有注释.为什么?当我将B(B&){}更改为B(const B&){}时,复制构造函数将更改回A(A const&).现在编译器认为A()的形式参数是const吗?这与标准有什么关系吗? (我正在使用gcc 4.2.4.) 解决方法
只有在可行的情况下,类A的隐式复制构造函数的签名才是A(const A&).当你取消注释B b时; line,此复制构造函数不可行,因为B的复制构造函数需要非const输入参数.
// Illegal implicit copy constructor A::A(const A& a) : b(a.b),// This line would be illegal because a.b is const i(a.i) { } 在这种情况下,隐式复制构造函数也是非const版本:A(A&);. // Legal implicit copy constructor A::A(A& a) : b(a.b),// Fine: a.b is now non-const i(a.i) { } 这是解释B b的原因;在类定义中更改隐式复制构造函数,从而更改程序行为. 编辑:不直接相关,但为了完整起见:如果B没有可访问的复制构造函数(因为它被声明为私有或删除),A将没有隐式复制构造函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |