ODR规则

C++ 语言中, 有一个重要的规则就是one definition rule。

  1. 在任何一个 translation unit, 模板 template, 类型type, 函数function, or 对象object 只能有一个 definition(定义). 但允许有多declarations.
  2. 在整个program中, 一个object 和一个 non-inline function 不能有超过一个定义; 要想使用这个 object 或者这个function, 那么必须保证他们只有一个definition. You can declare an object or function that is never used, in which case you don't have to provide a definition. In no event can there be more than one definition(在任何情况下不能有超过一个定义, 即使你再程序中并没有用到他们).
  3. Some things, like types, templates, and extern inline functions,可以定义在不同的 translation unit中. 但是对于一个给定的实体(For a given entity, each definition must be the same) 每一个定义必须相同. Non-extern objects and functions in different translation units are different entities, even if their names and types are the same.
一些违反ODR规则的程序可以通过Compiler 检测数来。


下面给几个关于ODR的例子。

ex1: In general, a translation unit shall contain no more than one definition of any class type. In this example, two definitions of the class type C occur in the same translation unit. This typically occurs if a header file is included twice by the same source file without appropriate header guards(头文件在同一个源程序中多次被包含了).



In the following, forming a pointer to S or defining a function taking a reference to S(并不需要S的定义) are examples of legal constructs, because they do not require the type of S to becomplete. Therefore, a definition is not required.

Defining an object of type S(定义类型S的对象), a function taking an argument of type S(一个函数吃一个类型为S的参数), or using S in a sizeof expression are examples of contexts where S must be complete, and therefore require a definition(均为需要S的定义的例子)。


具有多个定义的情况

在某些情况下, 可能会出现关于一个type 或者template的多个定义的情况。 当一个program含有多个头文件(multiple header files)和多个源文件(multiple source files)(头文件虽然只是一个特殊的源文件, 这里将其余常规的源文件区分开了), 此时常就会出现对于一个type 的多个定义的情况了。 但是无论如何, 我们都要求每一个translation unit 只能有一个 type的定义。 并且所有的关于type的定义都是等价的。

在最新的C++标准中, 关于static const data member 的定义(注意关于static的定义并没有改变)

In pre-standard C++, all static data members required a definition outside of their class. However, during the C++ standardization process it was decided to lift this requirement for static const integral members. The intent was to allow uses such as:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值