Inline constructors and One Definition Rule

纵饮孤独 提交于 2019-12-18 07:02:49

问题


Consider following source files 1.cpp

#include <iostream>

using namespace std;

struct X
{
    X()
    {
        cout << "1" << endl;
    }
};

void bar();

void foo()
{
    X x;
}

int main()
{
    foo();
    bar();
    return 0;
}

2.cpp

#include <cstdio>

struct X
{
    X()
    {
        printf("2\n");
    }
};

void bar()
{
    X x;
}

Is program compiled from these files well-formed? What should be in it's output?

I've expected linker error due to violation of One Definition Rule or output "1 2". However it prints out "1 1" when compiled with g++ 3.4 and VC 8.0.
How this can be explained?


回答1:


This does violate ODR (3.2) - specifically that you can have more than one definition of an inline function, but those definitions must be identical (3.2/5) - and leads to undefined behavior, so anything may happen and the compiler/linker is not required to diagnose that. The most likely reason why you see that behavior is that function calls are inlined and do not participate in linking, so no link error is emitted.




回答2:


It is undefined behaviour (with no required diagnostic) if inlined functions (such as your class constructor) have different definitions in different translation units.



来源:https://stackoverflow.com/questions/9389977/inline-constructors-and-one-definition-rule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!