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;
};
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
does in fact refer to a non-volatileconst
object with internal linkagef()
.2
.f()
.The point "It is not odr-used" is supposed to mean "It is not odr-used within
f()
" -- i.e. it doesn't breakf()
if you happen to odr-useCONSTANT
elsewhere in the program.