如何只在一个编译单元中使用的类型违反了单一定义规则? [英] How can a type that is used only in one compilation unit, violate the One Definition Rule?

查看:386
本文介绍了如何只在一个编译单元中使用的类型违反了单一定义规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被告知,这些类型,在那里可以看到有自己独特的翻译单位,违反了单一定义规则。有人可以解释一下吗?

I was told that these types, that are visible in there own unique translation unit, were in violation of the One Definition Rule. Can someone explain this?

//File1.cpp
#include "StdAfx.h"
static struct S { int Value() { return 1; } } s1;
int GetValue1() { return s1.Value(); }

//File2.cpp
#include "StdAfx.h"
static struct S { int Value() { return 2; } } s2;
int GetValue2() { return s2.Value(); }

// main.cpp
#include "stdafx.h"
extern int GetValue1();
extern int GetValue2();
int _tmain(int argc, _TCHAR* argv[])
{
    if( GetValue1() != 1 ) throw "ODR violation";
    if( GetValue2() != 2 ) throw "ODR violation";
    return 0;
} 

我知道如何解决这个问题。根据标题,我在寻找为什么它是一个ODR违反。它如何违反:在任何翻译单元中,模板,类型,函数或对象只能有一个定义。

I know how to fix the problem. As per the title, I was looking to why it was a ODR violation. How does it violate: "In any translation unit, a template, type, function, or object can have no more than one definition."? Or maybe it violates a different part of the rule.

推荐答案

您已定义 struct S 以两种不同的方式在全局命名空间中,这打破了单一定义规则。特别是,有两个不同的定义 :: S :: Value(),它是未定义的,它实际上会被调用。

You have defined struct S in the global namespace in two different ways, which breaks the One Definition Rule. In particular, there are two different definitions of ::S::Value(), and it's undefined which will actually end up being called.

您应该使用无名命名空间来确保在每个翻译单元中定义了 struct S 的明确命名版本:

You should use nameless namespaces to make sure a distinctly named version of struct S is defined in each translation unit:

namespace { struct S {int Value() {return 1;}} s1; }
int GetValue1() {return s1.Value();}

更多的单一定义规则比你引用的第一段。最后一段基本上说,一些事情,包括类定义,在程序中可以出现不止一次,只要它们都是相同的。你的代码打破了这最后一个条件。或者,在标准的(节略)词:

There's a lot more to the One Definition Rule than the first paragraph which you quote. The last paragraph basically says that some things, including class definitions, can appear more than once in a program, as long as they are all identical. Your code breaks this last condition. Or, in the (abridged) words of the Standard:


可以有一个类类型的多个定义...在程序,条件是每个定义出现在不同的翻译单元中,并且假定这些定义满足以下要求。给定这样的在多个翻译单元中定义的D实体,则D的每个定义将由相同的令牌序列组成。

There can be more than one definition of a class type ... in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then each definition of D shall consist of the same sequence of tokens.

这篇关于如何只在一个编译单元中使用的类型违反了单一定义规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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