上一篇帖子详细讨论了迟绑定的原理,那么,什么时候编译器会进行迟绑定呢?或者编译器根据什么来决定要不要进行迟绑定呢?
C++编程思想说:
It’s important to realize that upcasting deals only with addresses.
If the compiler has an object, it knows the exact type and therefore (in
C++) will not use late binding for any function calls – or at least, the
compiler doesn’t need to use late binding.
因为,迟绑定总是和向上转型联系在一起的(如果没有UpCasting,那么就不能进行迟绑定)。而UpCasting总是和地址或者引用联系在一起的。此时,就会进行迟绑定。但是,如果编译器处理一个对象,它确切的知道他的类型(迟绑定时不知道确切类型)。所以,编译器对这个对象调用函数时,因为效率的考量,就会进行早绑定。
例子如下:来自C++编程思想
这里,p1和p2调用函数时,都是迟绑定,因为此时不知道具体的对象类型,要通过地址和引用来处理。而p3的类型是确定的,调用函数时,执行的是早绑定。