c++/6546: static const members optimization failure
Gabriel Dos Reis
gdr@codesourcery.com
Thu Jun 27 23:42:00 GMT 2002
Nathan Myers <ncm-nospam@cantrip.org> writes:
| I thought folks on this list should know about this. In short,
| the "will-not-fix" below means that on gcc-3.1, as in 3.0, and
| maybe in 3.2 and beyond, in
|
| struct foo { static const int bar = 3; };
| int f(int i) { return std::min(foo::bar, i); }
|
| the compiler actually generates code to load the static value
| for foo::bar from memory each time (twice, in the code above),
| instead of using the manifest constant 3 in its place.
I don't know why loading twice. But I can understand loading once,
and I'm not sure I would qualify the behaviour as a bug.
std::min() expect an lvalue, foo::bar is such a thing, therefore its
the designated object's address is taken; thyen its definition is
required. Anything after that is optimization, optimization that
can't change the semantics. Therefore the definition is required.
| Furthermore, it insists on having a int foo::bar defined
| someplace, creating a porting difficulty from other compilers
| that don't.
Well, I think it is assuming the compiler will not require the
definition that is the non-portable assumption.
|
| Better dust off the old "member enum" trick if you hope to get
| compile-time-constant performance with static-const members.
| As an alternative, casting the value:
|
| int g(int i) { return std::min(int(foo::bar), i); }
|
| seems to work around the problem.
Indeed, that use doesn't need the address of the object, so the
compiler is free to apply any relevant optimization.
-- Gaby
More information about the Libstdc++
mailing list