Why can't run-time polymorphism be solved at compile time?

前端 未结 6 804
情书的邮戳
情书的邮戳 2020-12-07 14:27

Consider:

#include
using namespace std;

class Base
{
    public:
        virtual void show() { cout<<\" In Base \\n\"; }
};

class Der         


        
6条回答
  •  时光取名叫无心
    2020-12-07 14:44

    Compilers routinely devirtualise such calls, when the static type of the object is known. Pasting your code as-is into Compiler Explorer produces the following assembly:

    main:                                   # @main
            pushq   %rax
            movl    std::cout, %edi
            movl    $.L.str, %esi
            movl    $12, %edx
            callq   std::basic_ostream >& std::__ostream_insert >(std::basic_ostream >&, char const*, long)
            xorl    %eax, %eax
            popq    %rdx
            retq
    
            pushq   %rax
            movl    std::__ioinit, %edi
            callq   std::ios_base::Init::Init()
            movl    std::ios_base::Init::~Init(), %edi
            movl    std::__ioinit, %esi
            movl    $__dso_handle, %edx
            popq    %rax
            jmp     __cxa_atexit            # TAILCALL
    
    .L.str:
            .asciz  "In Derived \n"
    

    Even if you cannot read assembly, you can see that only "In Derived \n" is present in the executable. Not only has dynamic dispatch been optimized out, so has the whole base class.

提交回复
热议问题