内联构造函数和单一定义规则 [英] Inline constructors and One Definition Rule

查看:404
本文介绍了内联构造函数和单一定义规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的源文件
1.cpp

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?

由于违反一个定义规则或输出1 2,我预计链接器错误。但是,当使用g ++ 3.4和VC 8.0编译时,它打印出1 1。

如何解释?

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?

推荐答案

这违反了ODR(3.2) - 特别是你可以有一个以上的内联函数定义,但是这些定义必须是相同的(3.2 / 5) - 并导致未定义的行为,所以任何可能发生,编译器/链接器不需要诊断。您看到这种行为的最可能原因是函数调用是内联的,不参与链接,因此不会发出链接错误。

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.

这篇关于内联构造函数和单一定义规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆