legaliz...@mail.xmission.com (Richard) wrote in news:m40s34$mq3$1
@
news.xmission.com:
> Here's how I look at it: constants declared in a header are meant to
> be referenced from multiple translation units and the constant should
> follow ODR.
The constants are meant to be "used", not "referenced". You don't need to
keep around a reference or pointer to a const value as it cannot change
(legally).
> When you declare things static in the header, you end up
> with one definition per translation unit and depending on how often
> this header is included, you can end up with tons of data bloat.
The C++ rules for const namespace scope variables allow to optimize them
completely away in most cases where they are used, not to speak about the
TU-s where they are not used. Also the linker could presumably sometimes
merge different definitions into one.
I guess this works well for scalar types used by value, like int.
Declaring them extern and defining in a single TU would mean a
pessimization, as it would be then harder to inline the constant value
directly in the generated code.
For compound types this becomes more problematic, as these tend to be
used by references (e.g. const std::string&) and then it is probably
harder for the compiler+linker to optimize or merge them.
OTOH, declaring them extern does not really solve the problem either,
because they typically require dynamic initialization, so declaring them
extern could easily lead to "static initialization order fiasco".
Cheers
Paavo