【发布时间】:2012-12-17 11:59:59
【问题描述】:
关于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("\nA\n");
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。)
【问题讨论】:
标签: c++ templates constructor copy implicit