James Kanze wrote:
kwikius wrote:
> If you use the address of the int then it must be allocated
> space. If you dont take its address then the compiler can
> probably figure out that it doesnt need to allocate space so
> you wont see it in the image (I think the guarantee is even
> stronger inside a class). Of course with the define you cant
> take its address.
You can't explicitly take its address. You can still pass it as
a const reference, and the compiler will have to take its
address.
If you use the first form, you are guaranteed that the there
will be only one copy, since the language requires that the
address always be the same. If you use the #define, there's no
such guarantee, and you may end up with multiple copies, or
temporary copies which are reinitialized each time around.
The upshot of it all is that the clean solution is also the most
efficient one in terms of space and runtime.
Actually I remember that use of static const ints inside classes caused
problems and so I switched to using enums. Below is an example that
shows the problem in gcc 4.0( and probably other gcc versions) when
S::value is defined as an static const int , but disappears if its
defined as an enum. Note that the code links fine either way in VC7.1,
the other compiler tested. I have no idea who is correct.
#include <iostream>
struct S{
#if(1)
static int const value =1;
#else
enum{value =1};
#endif
};
int f( const int & n){return n;}
int main()
{
int n = f(S::value);
std::cout << n << '\n';
}
When S::value is a static const int the gcc linker complains:
test.o:test.cpp:(.text+0x27): undefined reference to `S::value'
collect2: ld returned 1 exit status
regards
Andy Little
mode. But since comeau does not link (and some of the intricacies in
unanswered.
[ comp.lang.c++.moderated. First time posters: Do this! ]