一个定义规则:能相应的实体有不同的名字? [英] One Definition Rule: Can corresponding entities have different names?

查看:148
本文介绍了一个定义规则:能相应的实体有不同的名字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了又看有关ODR在C ++标准的相关条款,但这个问题仍然向我敞开。标准说,内联函数的定义应出现在每个转换单元在其被使用,并且该定义应是其中几乎在一个页中记载的感相同。它说,该令牌序列必须是相同的。是否包括本地标识符名称?

在换句话说 请问下面的程序违反ODR?(我试图与Visual Studio 2008测试它自己,得到0错误和0警告。但我猜这并不能证明什么,因为我再变为例,两种完全不同的定义,仍然得到0错误和0警告。在MSVC的借口,应该指出的是,没有诊断是正式要求对违反ODR的)。

  //的main.cpp
内联INT F(INT);
诠释主(){
   F(3);
}
INT F(INT X){
   诠释Z = X;
   返回Z * Z者除外;
}//other.cpp
内联INT F(INT XX){
   INT ZZ = XX;
   返回ZZ ZZ *;
}


解决方案

标识符是一种令牌,每个标识符是一个独立的象征,所以是的,你需要有相同的标识符尊重ODR。它可以使在检测该编译器的差别(有人准备建立与导出的模板科莫的例子吗?它可以检测到一些违反ODR的)。

然后是C和C ++这里之间的差。 C没有的ODR和一般在C99内联函数的规则(有没有内联函数在C90)对那些C ++完全不同。在C99,你的code是正确的。事实上,你可以提供完全不同的定义。结果是,在C(而不是在C ++中),如果使用相同的定义和定义具有静态成员,你作为TU使用功能其实已经尽可能多的静态变量。

I read and reread the relevant clauses about ODR in the C++ standard, but this question still remains open to me. The standard says that the definition of an inline function shall appear in every translation unit in which it is used, and the definitions shall be identical in a sense which is described in almost a page. It says the token sequence must be the same. Does it include the local identifier names?

In other words does the following program violate the ODR? (I tried to test it myself with Visual Studio 2008 and got 0 errors and 0 warnings. But I guess this doesn't prove anything, because I then changed the example to two completely different definitions and still got 0 errors and 0 warnings. In excuse of MSVC it should be noted that no diagnostic is formally required for violations of ODR).

//main.cpp
inline int f(int);
int main(){
   f(3);
}
int f(int x){
   int z = x;
   return z*z;
}

//other.cpp
inline int f(int xx){
   int zz = xx;
   return zz*zz;
}

解决方案

Identifier is a kind of token, each identifier is a separate token, so yes, you need to have the same identifier to respect the ODR. It can make a difference in a compiler which detect this (someone ready to build an example for como with exported template? it can detect some violation of the ODR).

Then there is a difference between C and C++ here. C doesn't have the ODR in general and the rules for inline function in C99 (there is no inline functions in C90) are quite different to those of C++. In C99, your code is correct. In fact you can provide completely different definition. A consequence is that in C (but not in C++), if you use the same definition and that definition has a static member, you have in fact as many static variables as TU using the function.

这篇关于一个定义规则:能相应的实体有不同的名字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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