当 auto 遇到多态和虚函数时,正确的行为是什么?
What's the right behavior when auto meets polymorphism and virtual function?
class B {
public:
virtual void f(){
printf("B\n");
}
};
class D : public B {
public:
void f() {
printf("D\n");
}
};
int main(void)
{
B* d = new D();
d->f();
auto b = *d;
b.f();
}
对于d->f();
,输出是D
。这是对的。
但是对于 b.f();
,输出是 B
。 这样对吗?
Is this right?
没错,类型是在编译时推导的。 auto
uses the same rules of template argument deduction类型推导,基于static类型,不考虑动态多态
对于这种情况,d
的类型是B*
,那么*d
的类型是B
,所以b
的类型就是B
。那么*d
就会slicing copied到b
,因为b.f()
应该调用B::f()
。
代码等价于下面可能更清晰。
B b = *d;
b.f();
class B {
public:
virtual void f(){
printf("B\n");
}
};
class D : public B {
public:
void f() {
printf("D\n");
}
};
int main(void)
{
B* d = new D();
d->f();
auto b = *d;
b.f();
}
对于d->f();
,输出是D
。这是对的。
但是对于 b.f();
,输出是 B
。 这样对吗?
Is this right?
没错,类型是在编译时推导的。 auto
uses the same rules of template argument deduction类型推导,基于static类型,不考虑动态多态
对于这种情况,d
的类型是B*
,那么*d
的类型是B
,所以b
的类型就是B
。那么*d
就会slicing copied到b
,因为b.f()
应该调用B::f()
。
代码等价于下面可能更清晰。
B b = *d;
b.f();