在符合ODR的标头文件中使用常量 [英] using constants in header file with ODR compliance
问题描述
看着另一个问题,我意识到我不能通过头文件使用匿名命名空间中的对象或函数,因为这会导致类定义或内联函数中的ODR违规.如果是这种情况,那么是否可以在inline
函数或类中安全使用命名为const
或constexpr
static
的对象?例如,如果CONSTANT
位于下面的namespace
内部,将是不安全的,但是可以使用带有静态链接的常量吗?
Looking at another question I realized that I can't use objects or functions from an anonymous namespace through a header file since it'll cause ODR violations in class definitions or inline functions. If this is the case, then is it possible to use named const
or constexpr
static
objects in inline
functions or in classes safely? For example, if CONSTANT
was inside of namespace
below it would be unsafe, but is it okay to use a constant with static linkage?
// some header file to be included by multiple .cpp files
static const/*expr*/ int CONSTANT = 2;
inline int f() {
return CONSTANT;
}
class Cls {
int mem = CONSTANT;
};
推荐答案
此代码正常.完整的段落(C ++ 14 [basic.def.odr/6.2])是:
This code is OK. The full paragraph (C++14 [basic.def.odr/6.2]) is:
在D
的每个定义中,对应的名称(按照3.4查找)应指代
D
的定义内定义的实体,或应指代相同的实体,在重载解析后和部分匹配后模板专门化,除了名称可以引用非易失性 具有内部链接或无链接的const对象,如果该对象在所有D
定义中具有相同的文字类型,并且该对象使用常量表达式初始化,并且该对象不是 odr-used ,并且该对象在D
的所有定义中都具有相同的值;和
in each definition of
D
, corresponding names, looked up according to 3.4, shall refer to an entity defined within the definition ofD
, or shall refer to the same entity, after overload resolution and after matching of partial template specialization, except that a name can refer to a non-volatile const object with internal or no linkage if the object has the same literal type in all definitions ofD
, and the object is initialized with a constant expression, and the object is not odr-used, and the object has the same value in all definitions ofD
; and
此用法确实符合……和……与……除外"部分中的所有条件:
This usage does match all of the conditions in the "except ... and ... and ..." part:
- 名称
CONSTANT
实际上确实是指具有内部链接的非易失性const
对象 - 在
f()
的所有定义中它具有相同的文字类型. - 使用常量表达式
2
对其进行初始化. - 它不是使用过的.
- 在
f()
的所有定义中它具有相同的值.
- The name
CONSTANT
does in fact refer to a non-volatileconst
object with internal linkage - It has the same literal type in all definitions of
f()
. - It is initialized with a constant expression
2
. - It is not odr-used.
- It has the same value in all definitions of
f()
.
它不是 odr用过的"这一点应该表示它不是f()
内的 odr用过的" –即,它不是如果碰巧在程序的其他地方 odr-use CONSTANT
,请中断f()
.
The point "It is not odr-used" is supposed to mean "It is not odr-used within f()
" -- i.e. it doesn't break f()
if you happen to odr-use CONSTANT
elsewhere in the program.
这篇关于在符合ODR的标头文件中使用常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!