Why does the ld linker allow multiple class definitions with the same methods?

前端 未结 1 935
忘掉有多难
忘掉有多难 2021-01-01 17:55

Consider this file, first.cpp, containing a class definition and use:

#include 

struct Foo
{
    Foo(){ std::cout << \"Fo         


        
相关标签:
1条回答
  • 2021-01-01 18:31

    Again, Undefined Behavior. Your program has multiple definitions for the destructor of Foo, which means that it is in violation of the ODR. The program is wrong and anything can happend.

    Why does the linker not pick it up? When a function is defined inside the class definition, it is implicitly inline. Compilers usually mark those functions as 'weak symbols'. The linker then gets all translation units and tries to resolve the symbols. Weak symbols will be dropped by the linker if needed (i.e. if the symbol is already defined somewhere else).

    As of the actual output of the program, it looks like the compiler did not actually inline the call to the constructor and thus dispatched at runtime to the symbol that was left by the linker (the non-weak one)


    Why linker allows to have duplicate methods?

    Because all (but at most one) are weak symbols (i.e. inline)

    Why, in this case, wrong ~Foo() is printed?

    Because the call was not inlined, and the linker dropped the weak symbol

    0 讨论(0)
提交回复
热议问题