Reputation: 860
I have encountered this T.C.'s amazing answer (edit: which I now consider wrong) and have a follow-up question. Please consider a code where I use constantly initialized constant variables of integral types declared in global namespace scope to either constantly initialize constant static data members or declare array data members of my classes. Example for better illustration:
const int internal_linkage_constant = 1;
class ExternalLinkageClass
{
static const int constexpr_value = internal_linkage_constant; // #1
int arr[internal_linkage_constant]; // #2
};
Definitions of all these classes are in header files and might be shared among multiple translation units. Global constants must be defined before these definitions and inherently cannot have external linkage in order to be used in constant expressions. Now my question is: do such initializations lead to undefined behavior due to ODR violation?
Upvotes: 1
Views: 94
Reputation: 860
No by exception. The C++98 standard states in chapter 3.2 that:
There can be more than one definition of a class type, (…) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements:
- each definition of D shall consist of the same sequence of tokens; and
- in each definition of D, corresponding names, looked up according to 3.4, shall refer to an entity defined within the definition of D, or shall refer to the same entity, after overload resolution (13.3) and after matching of partial template specialization (14.8.3), except that a name can refer to a const object with internal or no linkage if the object has the same integral or enumeration type in all definitions of D, and the object is initialized with a constant expression (5.19), and the value (but not the address) of the object is used, and the object has the same value in all definitions of D;
- (…)
Upvotes: 3