问题描述
看着另一个问题,我意识到我不能通过头文件使用匿名命名空间中的对象或函数,因为这会导致类定义或内联函数中的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:
此用法确实符合……和……与……除外"部分中的所有条件:
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的标头文件中使用常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!