Consider the following header and assume it is used in several TUs:
static int x = 0;
struct A {
A() {
++x;
printf("%d
", x);
}
};
As this question explains, this is an ODR violation and, therefore, UB.
Now, there is no ODR violation if our inline
function refers to a non-volatile
const
object and we do not odr-use it within that function (plus the other provisions), so this still works fine in a header:
constexpr int x = 1;
struct A {
A() {
printf("%d
", x);
}
};
But if we do happen to odr-use it, we are back at square one with UB:
constexpr int x = 1;
struct A {
A() {
printf("%p
", &x);
}
};
Thus, given we have now inline
variables, should not the guideline be to mark all namespace
-scoped variables as inline
in headers to avoid all problems?
constexpr inline int x = 1;
struct A {
A() {
printf("%p
", &x);
}
};
This also seems easier to teach, because we can simply say "inline
-everything in headers" (i.e. both function and variable definitions), as well as "never static
in headers".
Is this reasoning correct? If yes, are there any disadvantages whatsoever of always marking const
and constexpr
variables in headers as inline
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…