On Jul 22, 5:40 pm, Ian Collins <
[email protected]> wrote:
[...]
I still think the standard could restrict "if it is used in
the program" to be "if its address is taken in the program".
What other "use in the program" (sic) should require
a definition at namespace scope?
Creating a reference to it?
Formally, a variable (const or not) is an lvalue. Anytime the
lvalue is not immediately converted to an rvalue, you would need
the definition. In theory, at least.
Note that if you have something like:
struct Toto { static int const a = 42; };
and somewhere write:
std::vector<int> v;
v.push_back(Toto::a);
you need the definition, since vector:
ush_back uses pass by
reference. (In practice, vector:
ush_back is probably inlined,
and if the compiler actually inlines it, then it might not
really need the reference.)
I think it is rare to take the address of a static constant integer
Perhaps not that rare, if you remember that pass by reference
counts as "taking the address", and that a lot of templated
functions regularly use pass by reference, even when the
template is instantiated on an int.
and if you do so without providing the out-of-class definition
you will get a linker error that will be immediately fixed.
Typically, for something like v.push_back, you'll only get the
linker error if the compiler doesn't inline the code for some
reason.
The standard language makes it the compiler writer’s job to
decide when the out-of-class definition is required,
No. The standard language says that if the out-of-class
definition is absent, it is undefined behavior. Which means
that it's up to the user to get it right; the compiler writer
doesn't have to do anything.
meaning that code may work now, but some day somebody adds
code that requires that definition and then we get the linker
error and have to explain why the definition wasn't necessary
before (even though it technically was).
Technically, the definition was necessary; the compiler just
didn't detect the error. What you're proposing has the opposite
effect: the definition might not be necessary now, but some
change in the use of the class would make it necessary.
The simplest rule is to always provide the definition,
regardless of what the standard or the compiler require.