What does this C++ FAQ try to convey ?
You can take the address of a static member if (and only if) it has an out-of-class definition :
class AE {
// ...
public:
static const int c6 = 7;
static const int c7 = 31;
};
const int AE::c7; // definition
int f()
{
const int* p1 = &AE::c6; // error: c6 not an lvalue
const int* p2 = &AE::c7; // ok
// ...
}
However this compiles !
You use -O2
to compile. The compiler can optimize away the const int* p1 = &AE::c6;
assignment (as it has no effect) and therefore it does not need the address of AE::c6
in the final code, that's why it compiles.
It gives a linker error without optimization.
You also get a linker error if you start to use p1
(e.g. std::cout << p1 << p2 << std::endl;
) Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With